Home > Backend Development > Golang > Why Does My Go Program Hang Despite Setting GOMAXPROCS(2) and High CPU Usage?

Why Does My Go Program Hang Despite Setting GOMAXPROCS(2) and High CPU Usage?

Patricia Arquette
Release: 2024-12-11 04:45:14
Original
311 people have browsed it

Why Does My Go Program Hang Despite Setting GOMAXPROCS(2) and High CPU Usage?

Hang after Setting GOMAXPROCS(2)

You have configured the program to allow two concurrent threads using runtime.GOMAXPROCS(2). However, the program still encounters a hang while outputting numbers, even though the CPU utilization is high.

The issue arises due to the presence of a busy loop in the forever() function. A busy loop continuously runs without relinquishing control to the scheduler. In this case, the forever() function effectively consumes one of the available threads indefinitely.

This behavior interferes with the scheduler's ability to allocate the remaining thread to the show() function, which is why the program appears to hang. The show() function also introduces an inefficiency by sleeping for 1000 milliseconds between iterations.

Solution

To resolve this issue, you should remove the busy loop from the forever() function and implement a scheduling point within the show() function. A scheduling point allows the scheduler to reclaim control periodically, ensuring that all goroutines have an opportunity to run.

Here is the modified code:

func forever() {
    for {
        runtime.Gosched()
    }
}

func show() {
    for number := 1; number < 999999; number++ {
        time.Sleep(1000)
        runtime.Gosched()
        fmt.Println(number)
    }
}
Copy after login

By adding runtime.Gosched() at the end of the for loop in the show() function, you can eliminate the issue and allow the program to run smoothly.

The above is the detailed content of Why Does My Go Program Hang Despite Setting GOMAXPROCS(2) and High CPU Usage?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template