gpt4 book ai didi

Go Channel 和 go routine with pointer variables 所有 goroutines 都睡着了 - 死锁

转载 作者:IT王子 更新时间:2023-10-29 02:30:13 25 4
gpt4 key购买 nike

我整个晚上都在研究如何修复这个错误,但我没有成功。当我运行程序时出现以下错误:“所有 goroutines 都睡着了 - 死锁!”。我知道这是因为主程序在例程有可能执行其任务之前退出,我认为使用 sync.WaitGroup 会有所帮助但不是真的:/

我想设置一些例程并使用 channel 发送 url 以检查 http 状态代码。我想限制一个网站的并发调用数。我按照示例使用字符串而不是结构做同样的事情并且它起作用了。

任何帮助将不胜感激:)

package main

import (
"fmt"
"sync"
"time"
)

const (
numPollers = 2 // number of Poller goroutines to launch
)

var urls = []string{
"http://www.google.com/",
"http://golang.org/",
"http://blog.golang.org/",
"http://golangtutorials.blogspot.fr",
"https://gobyexample.com/",
}

// Resource represents an HTTP URL to be polled by this program.
type Resource struct {
url string
}

func Poller(in <-chan *Resource, wg *sync.WaitGroup) {
//defer wg.Done()
for r := range in {
fmt.Printf("Finished: %v - %v\n", r.url, time.Now())
}
wg.Done()
}

func main() {
var wg sync.WaitGroup
pending := make(chan *Resource)

wg.Add(len(urls))

go Poller(pending, &wg)

go func() {
for _, url := range urls {
wg.Add(1)
fmt.Println("SENT > Pending url " + url)
pending <- &Resource{url: url}
}
}()

wg.Wait()

fmt.Printf("Finished all goroutines: %v\n", time.Now())
}

https://play.golang.org/p/B-HSiDo2Qg

最佳答案

首先,您对 wg.Add() 的调用过多。你为你正在运行的每个 goroutine 调用一次。参见 http://golang.org/pkg/sync/#WaitGroup .其次,您在完成写入后没有关闭 channel 。这是您的代码的修改版本:

package main

import (
"fmt"
"sync"
"time"
)

const (
numPollers = 2 // number of Poller goroutines to launch
)

var urls = []string{
"http://www.google.com/",
"http://golang.org/",
"http://blog.golang.org/",
"http://golangtutorials.blogspot.fr",
"https://gobyexample.com/",
}

// Resource represents an HTTP URL to be polled by this program.
type Resource struct {
url string
}

func Poller(in <-chan *Resource, wg *sync.WaitGroup) {
defer wg.Done()
for r := range in {
fmt.Printf("Finished: %v - %v\n", r.url, time.Now())
}
}

func main() {
var wg sync.WaitGroup
pending := make(chan *Resource)

wg.Add(2)

go Poller(pending, &wg)

go func() {
defer close(pending)
defer wg.Done()
for _, url := range urls {
fmt.Println("SENT > Pending url " + url)
pending <- &Resource{url: url}
}
}()

wg.Wait()

fmt.Printf("Finished all goroutines: %v\n", time.Now())
}

https://play.golang.org/p/ucUlZEZMZM

关于Go Channel 和 go routine with pointer variables 所有 goroutines 都睡着了 - 死锁,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27494857/

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