Understanding goroutines

前端 未结 4 1573
情深已故
情深已故 2020-12-04 19:46

I\'m trying to understand concurrency in Go. In particular, I wrote this thread-unsafe program:

package main

import          


        
4条回答
  •  囚心锁ツ
    2020-12-04 20:22

    There are a few things to keep in mind about Go's goroutines:

    1. They are not threads in the sense of Java's or C++ threads
      • goroutines are more like greenlets
    2. The go runtime multiplexes the goroutines across the system threads
      • the number of system threads is controlled by an environment variable GOMAXPROCS and defaults to 1 currently I think. This may change in the future
    3. The way goroutines yield back to their current thread is controlled by several different constructs
      • the select statement can yield control back to the thread
      • sending on a channel can yield control back to the thread
      • doing IO operations can yield control back to the thread
      • runtime.Gosched() explicitly yields control back to the thread

    The behavior you are seeing is because the main function never yields back to the thread and is instead involved in a busy loop and since there is only one thread the main loop has no place to run.

提交回复
热议问题