首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >限制每秒ping主机名的次数

问限制每秒ping主机名的次数
EN

Stack Overflow用户
提问于 2016-10-01 04:34:21
回答 1查看 74关注 0票数 1

我正在写一个学习围棋的网络爬虫。

我目前的实现使用10个go例程来获取网站,我想限制每秒可以命中主机名的次数。

做这件事最好的(线程安全)方法是什么?

EN

回答 1

Stack Overflow用户

发布于 2016-10-01 12:50:49

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

代码语言:javascript
复制
// 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次。

代码语言:javascript
复制
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个进程。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/39799684

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档