gpt4 book ai didi

go - 为什么会有这样的结果?

转载 作者:行者123 更新时间:2023-12-01 21:16:40 25 4
gpt4 key购买 nike

我编写了一个golang脚本来扫描打开的端口并使用sync.WaitGourp来控制goroutine的数量。
当goroutine太大(例如2000)时,结果不同于1000。
类似于提前退出。代码显示如下

func worker(wg *sync.WaitGroup) {
for job := range jobs {
_, err := net.DialTimeout("tcp", fmt.Sprintf("%s:%d", job.host, job.port), time.Millisecond*1500)
if err != nil {
results <- Result{job, false}
} else {
results <- Result{job, true}
}
}
wg.Done()
}

func main() {
go func() {
for i := 1; i < 65535; i++ {
jobs <- Job{host, i}
}
close(jobs)
}()

go func() {
for result := range results {
if result.status {
fmt.Println(result.job, "open")
}
}
}()

wg := sync.WaitGroup{}
for i := 1; i < 1000; i++ {
wg.Add(1)
go worker(&wg)
}
wg.Wait()
}
当1000

{127.0.0.1 80} open{127.0.0.1 631} open{127.0.0.1 3306} open{127.0.0.1 6379} open{127.0.0.1 33060} open


当2000

{127.0.0.1 80} open{127.0.0.1 631} open


我希望2000输出所有端口,例如1000

最佳答案

工作人员完成后,关闭结果 channel 。在主goroutine中处理结果。

wg := sync.WaitGroup{}
for i := 1; i < 1000; i++ {
wg.Add(1)
go worker(&wg)
}

go func() {
for i := 1; i < 65535; i++ {
jobs <- Job{host, i}
}

// No more jobs, exit from worker loops.
close(jobs)

// Wait for workers to write all results and exit.
wg.Wait()

// No more results, exit from main loop.
close(results)

}()

for result := range results {
if result.status {
fmt.Println(result.job, "open")
}
}
View the complete program on the GoLang PlayGround

关于go - 为什么会有这样的结果?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63138653/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com