
php小编草莓在这篇文章中将向大家介绍一个常见的编程错误:致命错误:“所有 goroutine 都在睡觉 - 死锁!错误执行”。这是在Go语言中常见的错误之一,也是开发者们经常遇到的挑战之一。在本文中,我们将详细解释这个错误的原因和解决方法,帮助大家更好地理解和处理这个问题。无论是初学者还是有经验的开发者,都能从本文中获得有价值的信息和技巧。让我们一起来探索吧!
问题内容
我对 go 中的并发很陌生,所以我尝试了一个带有通道和 goroutine 的示例。我想要生产者-消费者模式。生产者函数永远给出随机字符串,消费者通过将它们变为大写来修改它们。我想在有限的时间(2 秒)内运行它。
package main
import (
"fmt"
"math/rand"
"strings"
"time"
)
func producer(x []string, c chan string) {
i := 1
for i > 0 {
randomIndex := rand.Intn(len(x))
pick := x[randomIndex]
c <p>我只收到一个数组元素和一些错误。需要进行哪些更改才能使此示例正常工作?</p><p>输出:</p><p>两个</p><p>致命错误:所有 goroutine 都在休眠 - 死锁!</p><div class="aritcle_card flexRow artxards">
<div class="artcardd flexRow">
<a class="aritcle_card_img" rel="nofollow" href="/xiazai/gongju/2525" title="Go语言(Golang)1.26.0"><img
src="https://img.php.cn/upload/manual/001/589/237/6a6adeed24a4a355.png" alt="Go语言(Golang)1.26.0" onerror="this.onerror='';this.src='/static/lhimages/moren/morentu.png'" ></a>
<div class="aritcle_card_info flexColumn">
<a rel="nofollow" href="/xiazai/gongju/2525" title="Go语言(Golang)1.26.0" class="overflowclass">Go语言(Golang)1.26.0</a>
<p class="overflowclass">Go语言(Golang)1.26.0版本官方下载,版本号 1.26.0,适合旧项目维护、兼容性测试和指定版本开发环境搭建。</p>
</div>
<a rel="nofollow" href="/xiazai/gongju/2525" title="Go语言(Golang)1.26.0" class="aritcle_card_btn flexRow flexcenter"><b></b><span>下载</span>
</a>
</div>
</div><p>goroutine 1 [chan receive]:
main.main()</p><p>协程 6 [chan send]:
main.生产者({0xc00004e040, 0x4, 0x0?}, 0x0?)
由 main 创建。主要的
退出状态2</p><h2 class="daan">解决方法</h2><p>您的消费者应该在循环中运行,这一点已经提到过。</p><p>更改consumer的第一个参数,使其为<code>chan字符串</code>而不是字符串。这样生产者就可以不断地向这个通道写入数据,以便消费者在另一个通道上发布,直到时间限制到期。</p><pre class="brush:php;toolbar:false;">func consumer(consumechan chan string, outch chan string) {
for {
select {
case s := <p>现在,在调用 <code>go consumer()</code> 之前的主函数中,您正在等待生产者对 <code>c1</code> 通道的第一个响应。不要这样做,而是将 <code>c1</code> 通道作为第一个参数传递。</p><pre class="brush:php;toolbar:false;">func main() {
s := []string{"one", "two", "three", "four"}
c1 := make(chan string)
d1 := make(chan string)
go producer(s, c1)
go consumer(c1, d1)
stop := time.After(2000 * time.Millisecond)
for {
select {
case <p>这应该显示生产者在 <code>c1</code> 通道上连续写入随机数,以及消费者在 d1 通道上连续写入所有大写文本,直到 2 秒结束。</p>










