Home > other >  To solve the language thread
To solve the language thread

Time:10-06

Tested the channel of go, do not close, feel there should be no error, but running tips deadlock, why, to solve? To have a buffer channel is at a deadlock error!!!!!!!!!!!!!!!!!!!
Package the main

Import (
"FMT"
)

Func main () {
Channel:=make (chan int)

Go func () {
For I:=0; i <5; I++ {
Ch & lt; -i
FMT. Println (I)
}
//close (channel)
} ()

For {
If num, ok:=& lt; - channel; Ok==true {
FMT. Println (" num=", num)
} else {
Break
}
}
}

CodePudding user response:

No actual debug the code, you think after analysis, this channel you are in the other five goroutine to write data, but write number is limited, but in the main goroutine you wrote an infinite loop, while other goroutine after launch, you can read because the channel forever block the main function,

CodePudding user response:

Num, ok:=& lt; - channel
When the channel is not close, such as channel with data num to have value, ok to true; No data block,
When the channel is close, such as channel data is same as above, countless according to the num of zero value, ok to false

CodePudding user response:

Ok to false

CodePudding user response:

Coroutines not asynchronous you need to have the corresponding to write an article, all you wrote blocking problem will happen, you should give the channel:=make chan (int) cache area such as: price channel:=make (chan int, 1024) at this time his store for 1 m just wasn't up to 1 m will have been written even if did not read the same until you reach 1 m after blocking the hope can help you

CodePudding user response:

Chanel is not close, num, ok:=& lt; - channel; Receive five times after the data has been blocked, and blocking in the circulation, causing a deadlock

CodePudding user response:

The original poster is mainly don't know the num, ok:=& lt; - channel; Whether this is ok chan is shut, you//close (channel) this commented out, so num, ok:=& lt; - channel ok is true forever, and this statement within the loop, not to a deadlock to blame,

CodePudding user response:

Problem has been solved, please

CodePudding user response:

I only saw the ch undefined

CodePudding user response:

Ok, don't the else
  • Related