golang WaitGroup 并发使用

前端之家收集整理的这篇文章主要介绍了golang WaitGroup 并发使用前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

题目原地址

package main

import (
    "fmt"
    "sync"
    "time"
    "sync/atomic"
)

const THREE_MINUTES = 3 * 60 * 1

type BanTable struct {
    VisTable map[string]int64
    Lock     *sync.Mutex
}

func NewBanTable() *BanTable {
    return &BanTable{
        VisTable: make(map[string]int64, 0),Lock:     new(sync.Mutex),}
}

func (self *BanTable) IsVisited(ip string) bool {
    self.Lock.Lock()
    defer self.Lock.Unlock()
    ts,ok := self.VisTable[ip]
    ret := false
    if ok && ts > 0 && time.Now().Unix()-ts < THREE_MINUTES {
        ret = true
    }
    if !ret {
        self.VisTable[ip] = time.Now().Unix()
    }
    return ret
}

func main() {
    var succ int64 = 0
    ban := NewBanTable()
    wg := new(sync.WaitGroup)
    for i := 0; i < 1000; i++ {
        for j := 0; j < 100; j++ {
            wg.Add(1)
            ip := fmt.Sprintf("192.168.1.%d",j)
            // 注意,若不注明参数类型,这里取外层的引用地址
            go func(ip string,wg *sync.WaitGroup,succ *int64) {
                defer wg.Done()
                if !ban.IsVisited(ip) {
                    atomic.AddInt64(succ, 1)
                }
            }(ip,wg,&succ)
        }
    }
    wg.Wait()
    fmt.Println("success:",succ)
}
原文链接:/go/187205.html

猜你在找的Go相关文章