php editor Xigua will answer your question about "the reason for the go routine behavior". The routine (goroutine) in the Go language is a lightweight concurrency mechanism that can achieve the effect of concurrent execution. However, in some cases, the behavior of go routines may have some unexpected results. This is mainly due to the scheduling mechanism of go routines and the characteristics of the memory model. Before we deeply understand the routine behavior of the Go language, we need to understand these features and their impact on program behavior.
I am reading a book called "Go in action" and I am a little confused about the goroutine part of the book. Basically I want to know two things about the following code thing:
package main import ( "fmt" "runtime" "sync" "time" ) var counter int = 0 var wg sync.WaitGroup var mtx sync.Mutex func main() { wg.Add(2) runtime.GOMAXPROCS(1) go incCounter("A") go incCounter("B") wg.Wait() fmt.Println(counter) } func incCounter(prefix string) { fmt.Println("Started thread ", prefix) defer wg.Done() mtx.Lock() { fmt.Println("Incrementing counter from ", prefix) counter = counter + 1 fmt.Println("Passing to another thread") runtime.Gosched() for i := 1; i < 100; i++ { time.Sleep(1 * time.Second) fmt.Println("Thread still executing ", prefix) } } mtx.Unlock() }
The output is:
Started thread B Incrementing counter from B Passing to another thread Started thread A Thread still executing B Thread still executing B Thread still executing B Thread still executing B
As I said, setting gomaxprox to 1 will allow only one Goroutine to be executed at a time, but in this case, that doesn't seem to be the case, in fact both Goroutines are running in parallel.
Goroutines run concurrently. This means that if there are processors available, the scheduler can schedule them to run in parallel. If only one processor is available, they will still run concurrently, but only one goroutine will be running at any given moment.
The Go runtime makes no guarantees about which goroutine will run first. So the running order of a group of newly created goroutines is random,
The above is the detailed content of Why does the go routine behave like this?. For more information, please follow other related articles on the PHP Chinese website!