英文:
Is possible the deadlock happened if we don't use channel?
问题
死锁发生在一组 goroutine 互相等待且没有一个能够继续执行的情况下。
例如:
func main() {
ch := make(chan int)
ch <- 1
fmt.Println(<-ch)
}
但是如果我们不使用通道,是否有可能发生死锁呢?
英文:
A deadlock happens when a group of goroutines are waiting for each other and none of them is able to proceed.
For example:
func main() {
ch := make(chan int)
ch <- 1
fmt.Println(<-ch)
}
But is there any possibility the deadlock happened if we don't use channel?
答案1
得分: 6
为了产生死锁,只需要一个(或多个)组件以一种无法继续进行的方式等待。
通道是在Go中经常遇到死锁的一种方式,但任何用于同步的东西都可能触发死锁。
以下是一些简单死锁的示例:
互斥锁(Mutex):
package main
import "sync"
func main() {
var mu sync.Mutex
mu.Lock()
mu.Lock()
}
WaitGroup(等待组):
package main
import "sync"
func main() {
var wg sync.WaitGroup
wg.Add(1)
wg.Wait()
}
英文:
In order to have a deadlock, you just need one (or more) components to be waiting in such a way that noone will proceed first.
A channel is a common way to experience a deadlock in Go, but anything that is used for synchronization can trigger it as well.
Here are just some examples of simple deadlocks:
Mutex:
package main
import "sync"
func main() {
var mu sync.Mutex
mu.Lock()
mu.Lock()
}
WaitGroup:
package main
import "sync"
func main() {
var wg sync.WaitGroup
wg.Add(1)
wg.Wait()
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论