如果我们不使用通道,死锁是否可能发生?

huangapple go评论85阅读模式
英文:

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 &lt;- 1
        fmt.Println(&lt;-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 &quot;sync&quot;

func main() {
	var mu sync.Mutex
	mu.Lock()
	mu.Lock()
}

WaitGroup:

package main

import &quot;sync&quot;

func main() {
	var wg sync.WaitGroup
	wg.Add(1)
	wg.Wait()
}

huangapple
  • 本文由 发表于 2021年9月29日 20:01:48
  • 转载请务必保留本文链接:https://go.coder-hub.com/69375989.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定