为什么这个Go代码被阻塞? [英] Why is this Go code blocking?

查看:107
本文介绍了为什么这个Go代码被阻塞?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我写了下面的程序:

  package main 

import(
fmt


func processevents(list chan func()){
for {
// a:=< -list
// a()
}
}

func test(){
fmt.Println(Ho!)
}

$ func main(){

eventlist:= make(chan func(),100)

去processevents(eventlist)

for {
eventlist< - test
fmt.Println(Hey!)
}
}

由于频道事件列表是一个缓冲频道,因此我认为我应该输出精确到100倍的输出Hey!,但它只显示一次。我的错误在哪里?

解决方案

Update(Go version 1.2 +)



<从Go 1.2开始,调度程序的工作原理是抢先式多任务
这意味着原始问题中的问题(以及下面提供的解决方案)不再相关。



Go 1.2发行说明


调度程序中的占先在以前的版本中,一个永远循环的goroutine可能会在同一线程上饿死其他goutoutine
,这是GOMAXPROCS只提供一个用户线程时的一个严重问题。
在Go> 1.2中,这是部分解决的:调度程序偶尔会在
入口函数中被调用。这意味着任何包含(非内联)函数
调用的循环都可以被抢占,从而允许其他goroutine在同一个线程上运行。




简短回答



它不会阻止写入。它卡在 processevents 的无限循环中。
这个循环永远不会对调度器产生影响,导致所有的goroutine无限期地锁定。



如果您将 processevents ,你会得到预期的结果,直到第100次写。在这一点上,程序恐慌,因为没有人从频道读取。



另一个解决方案是调用 runtime.Gosched() code>在循环中。



长答案



使用Go1.0.2,Go的调度程序工作合作多任务的原则。
这意味着它通过让这些例程在某些条件下与调度程序进行交互,将CPU时间分配给在给定OS线程中运行的各种goroutine。
当在goroutine中执行某些类型的代码时,会发生这些交互。
在go的情况下,这涉及到执行某种I / O,系统调用或内存分配(在某些情况下)。

在空循环的情况下,从来没有遇到过这样的情况。因此,只要该循环正在运行,调度程序就绝不允许运行其调度算法。因此,它会阻止它将CPU时间分配给等待运行的其他例程,并且观察到的结果如下:您实际上创建了无法检测到或由调度程序中断的死锁。



在Go中通常不需要空循环,并且在大多数情况下会指示程序中的错误。如果您确实需要它,无论出于何种原因,您必须通过在每次迭代中调用 runtime.Gosched()手动屈服于调度程序。


$ $ {
runtime.Gosched()
}


  b 
$ b

GOMAXPROCS 设置为一个值> 1 被提及为解决方案。虽然这将消除您观察到的即时问题,但如果调度程序决定将循环的goroutine移至其自己的OS线程,它将有效地将问题移至不同的OS线程。除非您在 processevents 函数的开头调用 runtime.LockOSThread(),否则无法保证。即使如此,我仍然不会依赖这种方法来成为一个好的解决方案。只需在循环中调用 runtime.Gosched()即可解决所有问题,无论运行哪个操作系统线程。


I wrote the following program:

package main

import (
    "fmt"
)

func processevents(list chan func()) {
    for {
        //a := <-list
        //a()
    }
}

func test() {
    fmt.Println("Ho!")
}

func main() {

    eventlist := make(chan func(), 100)

    go processevents(eventlist)

    for {
        eventlist <- test
        fmt.Println("Hey!")
    }
}

Since the channel eventlist is a buffered channel, I think I should get at exactly 100 times the output "Hey!", but it is displayed only once. Where is my mistake?

解决方案

Update (Go version 1.2+)

As of Go 1.2, the scheduler works on the principle of pre-emptive multitasking. This means that the problem in the original question (and the solution presented below) are no longer relevant.

From the Go 1.2 release notes

Pre-emption in the scheduler

In prior releases, a goroutine that was looping forever could starve out other goroutines on the same thread, a serious problem when GOMAXPROCS provided only one user thread. In Go > 1.2, this is partially addressed: The scheduler is invoked occasionally upon entry to a function. This means that any loop that includes a (non-inlined) function call can be pre-empted, allowing other goroutines to run on the same thread.

Short answer

It is not blocking on the writes. It is stuck in the infinite loop of processevents. This loop never yields to the scheduler, causing all goroutines to lock indefinitely.

If you comment out the call to processevents, you will get results as expected, right until the 100th write. At which point the program panics, because nobody reads from the channel.

Another solution is to put a call to runtime.Gosched() in the loop.

Long answer

With Go1.0.2, Go's scheduler works on the principle of Cooperative multitasking. This means that it allocates CPU time to the various goroutines running within a given OS thread by having these routines interact with the scheduler in certain conditions. These 'interactions' occur when certain types of code are executed in a goroutine. In go's case this involves doing some kind of I/O, syscalls or memory allocation (in certain conditions).

In the case of an empty loop, no such conditions are ever encountered. The scheduler is therefore never allowed to run its scheduling algorithms for as long as that loop is running. This consequently prevents it from allotting CPU time to other goroutines waiting to be run and the result you observed ensues: You effectively created a deadlock that can not be detected or broken out of by the scheduler.

The empty loop is usually never desired in Go and will, in most cases, indicate a bug in the program. If you do need it for whatever reason, you have to manually yield to the scheduler by calling runtime.Gosched() in every iteration.

for {
    runtime.Gosched()
}

Setting GOMAXPROCS to a value > 1 was mentioned as a solution. While this will get rid of the immediate problem you observed, it will effectively move the problem to a different OS thread, if the scheduler decides to move the looping goroutine to its own OS thread that is. There is no guarantee of this, unless you call runtime.LockOSThread() at the start of the processevents function. Even then, I would still not rely on this approach to be a good solution. Simply calling runtime.Gosched() in the loop itself, will solve all the issues, regardless of which OS thread the goroutine is running in.

这篇关于为什么这个Go代码被阻塞?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆