我正在写一个学习围棋的网络爬虫。
我目前的实现使用10个go例程来获取网站,我想限制每秒可以命中主机名的次数。
做这件事最好的(线程安全)方法是什么?
发布于 2016-10-01 12:50:49
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
}单个go例程等待每个自动收报机事件,并尝试将缓冲通道填满至最大容量。如果使用者没有耗尽缓冲区,那么任何后续的tick都只会重新填充它。您可以使用通道在每个duration中同步执行最多n次的操作。例如,我可能希望每秒调用doSomething()的次数不超过5次。
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(),这将在每个的每秒中展开最多5个进程。
https://stackoverflow.com/questions/39799684
复制相似问题