2016-09-30 49 views
1

我写一个网络爬虫学去限制的次主机数量的ping每秒

我的当前实现使用10个走程序,以获取网站,我想限制的时候,我可以打一个数主机名每秒。

什么是最好的(线程安全)方法来做到这一点。

+1

请发布一些代码示例 –

+1

请参阅:我如何在Golang中每秒执行多次命令:http://stackoverflow.com/questions/39385883/how-do-i-execute-commands-many-many -times每秒合golang – 2016-10-01 07:35:47

回答

1

A channel提供了一个可用于协调的并发同步机制。您可以使用一个与time.Ticker协调的定期分派给定数量的函数调用。

// A PeriodicResource is a channel that is rebuffered periodically. 
type PeriodicResource <-chan bool 

// The NewPeriodicResourcePool provides a buffered channel that is filled after the 
// given duration. The size of the channel is given as count. This provides 
// a way of limiting an function to count times per duration. 
func NewPeriodicResource(count int, reset time.Duration) PeriodicResource { 
    ticker := time.NewTicker(reset) 
    c := make(chan bool, count) 

    go func() { 
     for { 
      // Await the periodic timer 
      <-ticker.C 

      // Fill the buffer 
      for i := len(c); i < count; i++ { 
       c <- true 
      } 
     } 
    }() 

    return c 
} 

单程序例程会等待每个ticker事件并尝试将缓冲通道填充到最大容量。如果消费者没有消耗缓冲区,则任何连续的滴答只会补充它。您可以使用该频道同步执行最多ñ次/ 持续时间。例如,我可能想每秒钟拨打doSomething()不超过五次。

r := NewPeriodicResource(5, time.Second) 
for { 
     // Attempt to deque from the PeriodicResource 
     <-r 

     // Each call is synchronously drawing from the periodic resource 
     doSomething() 
} 

当然,相同的信道可被用于每第二调用go doSomething()这将风扇出至多过程。