[Golang Learning] goroutine scheduling

Source: Internet
Author: User
This is a creation in Article, where the information may have evolved or changed.

These two days some busy, study under Golang, indeed very concise.

But there are some drawbacks. In my test. Golang's Dispatch (Goroutine) does not seem very good.

int ) {        fmt. Println (k)}func main () {    runtime. Gomaxprocs (2)    for0; i++ {        go Say (i)    }    for  {    }}

There is a bug in this test code.

I didn't set it up at first.

Runtime. Gomaxprocs (2)

Because the for loop causes the main thread to block. All goroutine have no chance to execute.

After I had asked someone, I added this sentence.

This is the number of OS threads that set go.

But the result is a bit strange, sometimes output 100 k, sometimes output 50 k. or simply a K.

Why is it?

Because we have no control over which OS thread the Goroutine will be allocated.

So the only solution (the one I can see) is to take the initiative to surrender control in the for loop. Make the goroutine on the same OS thread an opportunity to be executed.

Like this:

for {
Runtime. Gomaxprocs (2)
}

Here is a detailed explanation of the GO scheduler:

Http://morsmachine.dk/go-scheduler

That is, the Goroutine queue for each OS thread in Golang, which switches when a thread is blocked. Switch to other threads to execute. But this often happens when I/O and system calls.

Why is Golang unable to switch goroutine to other threads when the pure for loop is blocked?

The runtime is automatically called internally by the I/O and system calls implemented by GO itself. Gomaxprocs (2)

The above does not have source code analysis as support. There may be fallacies. please tell me.

Golang should continuously improve the scheduler in subsequent releases.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.