【发布时间】:2013-05-21 17:34:26
【问题描述】:
我正在尝试实施“工人”系统,但在确定它为什么会自行死锁时遇到了一些问题
代码通过调用fillQueue()来执行
我不明白为什么我的代码最终处于解除锁定状态(一个进程在“process()”的第二行等待,从通道“queue”读取,而另一个在“fillQueue”的末尾等待()" 等待从服务员那里读取。
我不明白为什么它从来没有得到服务员的阅读。
func process(queue chan *entry, waiters chan bool) {
for {
entry, ok := <-queue
if ok == false {
break
}
fmt.Println("worker: " + entry.name)
entry.name = "whatever"
}
fmt.Println("worker finished")
waiters <- true
}
func fillQueue(q *myQueue) {
// fill our queue
queue := make(chan *entry, len(q.pool))
for _, entry := range q.pool {
fmt.Println("push entry")
queue <- entry
}
fmt.Printf("entry cap: %d\n", cap(queue))
// start the readers
var total_threads int
if q.maxConcurrent <= len(q.pool) {
total_threads = q.maxConcurrent
} else {
total_threads = len(q.pool)
}
waiters := make(chan bool, total_threads)
fmt.Printf("waiters cap: %d\n", cap(waiters))
var threads int
for threads = 0; threads < total_threads; threads++ {
fmt.Println("start worker")
go process(queue, waiters)
}
fmt.Printf("threads started: %d\n", threads)
for ; threads > 0; threads-- {
fmt.Println("wait for thread")
ok := <-waiters
fmt.Printf("received thread end: %b\n", ok)
}
}
这是我运行时的日志:
push entry
push entry
push entry
entry cap: 3
waiters cap: 1
start worker
threads started: 1
wait for thread
worker: name1
worker: name2
worker: name3
throw: all goroutines are asleep - deadlock!
【问题讨论】:
-
广告“我不明白为什么它从来没有得到服务员的阅读。”:没有最低限度,但完整没有其他人可以理解i> 和可编译的代码。许多死锁纯粹是基于,例如,使用的缓冲通道与非缓冲通道。