Home  >  Article  >  Backend Development  >  How to deal with deadlock in golang

How to deal with deadlock in golang

(*-*)浩
(*-*)浩Original
2019-12-30 15:37:372800browse

How to deal with deadlock in golang

Deadlock

Deadlock means that during the execution of two or more coroutines, due to competition for resources or due to each other A blocking phenomenon caused by communication. Without external force, they will not be able to advance. (Recommended learning: go)

Common deadlock

Scenario 1: A channel is read and written in a go process

func main() {
	c:=make(chan int)
	c<-88
	<-c
}

Scenario 2: Use the channel before the go process is started

func main() {
	c:=make(chan int)
	c<-88
	go func() {
		<-c
	}()
}

Scenario 3: Channel 2 is called in channel 1, and channel 1 is called in channel 2

func main() {
	c1,c2:=make(chan int),make(chan int)
	go func() {
		for  {
			select{
				case <-c1:
					c2<-10
			}
		}
	}()
	for  {
		select{
		case <-c2:
			c1<-10
		}
	}	
}

Deadlocks occur in many situations, but they are all caused by competition for resources and data communication.

The solution to deadlock is to lock.

The above is the detailed content of How to deal with deadlock in golang. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn