Home > other >  The go language small white for help, why not my son coroutines??
The go language small white for help, why not my son coroutines??

Time:11-19

Package the main

Import (
"FMT"
"Runtime"
)

Func test () {

For I:=0; i <5; I++ {
FMT. Println (" son coroutines hello ")
}
}

Func main () {

For I:=0; I<10; I++ {
Runtime. Gosched ()//let Lord coroutines release time slice
FMT. Println (" Lord coroutines hello ")
}
Go test ()
}
Why not my son coroutines execution? I have added the runtime Gosched (),

Then try once, unless add time. Sleep (time. Second) or exchange coroutines and main coroutines code sequence, is this why?

CodePudding user response:

Main coroutines if finished before child coroutines, so there is no output of coroutines,

In fact, are generally multi-core computer now, son coroutines or have the opportunity to output, but if you specify the number of CPU's nuclear, coroutines almost no chance to output, the following code:
 
Func main () {
//specified runtime. GOMAXPROCS (1) auditing
For I:=0; i <3; I++ {
Runtime. Gosched ()//let Lord coroutines release time slice
FMT. Println (" Lord coroutines hello ")
}
Go test ()
}

If you go the test () for this line mentioned before, the same problem, as long as the number of a for loop changes little, you will find that the son may not perform as coroutines,
Time. Sleep is also unreliable, if the child coroutines takes is long and may not have the complete output,

Make sure the child coroutines, can consider to use chanel or waitgroup
 

Var wg=sync. WaitGroup {}

Func test () {
For I:=0; i <5; I++ {
FMT. Println (" son coroutines hello ")
}
Wg. Done ()
}

Func main () {
//specified runtime. GOMAXPROCS (1) auditing
For I:=0; i <3; I++ {
.//the runtime Gosched ()//let the main coroutines give up time
FMT. Println (" Lord coroutines hello ")
}
Wg. The Add (1)
Go test ()
Wg. Wait ()
}

CodePudding user response:

The child coroutines could perform, main process is out of the race

CodePudding user response:

Go test ()
For I:=0; I<10; I++ {
Runtime. Gosched ()//let Lord coroutines release time slice
FMT. Println (" Lord coroutines hello ")
}

To go the test (s) in advance, what do you mean by on the back? Write behind, runtime. Gosched ()//let the main coroutines release time slice
Didn't perform to go at this time of the test (), you are not a white let time slice?

Most of is said above, use waitgroup to synchronization,
  • Related