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)
}
golang WaitGroup 并发使用
最新推荐文章于 2024-06-01 15:55:13 发布