Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

for-select reaches 100% CPU usage due to empty default definition in Golang

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading