When I run the following code, something is going wrong.
var ch chan int
for {
select {
case <-ch:
return
default:
}
}
What can I do to prevent 100% CPU usage?
>Solution :
If I understand you correctly, you want to solve 100% CPU usage problem.
var ch chan int
for {
select {
case <-ch:
return
default:
time.Sleep()
return
}
}
The reason for the CPU usage is this empty default, because when the condition of the case is not satisfied, the loop will go default and then execute the next loop, which causes a dead loop, so you cannot define an empty default when using the for-select statement. Accordingly, you can add a sleep() function to solve that.
I hope it will be helpful.