Notice that main is also a Goroutine.
The basic use
Subtasks performed with GO alternate (like time slices).
After the main goroutine exits, other work goroutine exits automatically (kind of parent-child process) :
package main import ( "fmt" "time" ) func newTask() { i := 0 for { i++ fmt.Printf("new goroutine: I = %d\n", I) time.sleep (1 * time.second)}} func main() {// Create a goroutine, Go newTask() I := 0 //main goroutine loop print for {I ++ ftt. Printf("main goroutine: = 0 ") I = %d\n", I) time.sleep (1 * time.second) // delay 1s} }Copy the code
The order of multiple coroutines is not certain.
var _ = runtime.GOMAXPROCS(3) var a, B int func u1() {a = 1 b = 2} func u2() {a = 3 b = 4} func p() {println(a) println(b)} func main() {go u1() // multiple Go u2() go p() time.sleep (1 * time.second)}Copy the code
The runtime package
Give up the time slice
Runtime.gosched () // Run the runtime.gosched () // run the runtime.gosched () // run the runtime.gosched ().
Runtime.goexit () // will immediately terminate the current goroutine execution, and the scheduler ensures that all registered deferred calls to defer are executed.
Package main import (" FMT "" Runtime" "time") // Calling Runtime.goexit () will immediately terminate the current goroutine execution, and the scheduler ensures that all registered deferred calls to defer are executed. Func main() {go func() {defer fmt.println (" a.doffer ") func() {defer fmt.println (" b.doffer ") runtime.goexit () // defer Goroutine, import "runtime" fmt.println ("B") // Will not execute}() defer fmt.println (" c.doffer ") // There is no time to register. For {time.sleep (1 * time.second)}} for {time.sleep (1 * time.second)}} //B.defer //A.deferCopy the code
GOMAXPROCS
The runtime.gomaxprocs () call is used to set the maximum number of CPU cores that can be evaluated in parallel and return the previous value.
Sample code:
Func main () {/ / n: = runtime. GOMAXPROCS (1) / / print results: 111111111111111111110000000000000000000011111... N: = the runtime GOMAXPROCS (2) / / print results: 010101010101010101011001100101011010010100110... fmt.Printf("n = %d\n", n) for { go fmt.Print(0) fmt.Print(1) } }Copy the code
At the first execution (runtime.gomaxprocs (1)), at most one Goroutine can be executed simultaneously. So it prints a lot of ones.
After some time, the GO scheduler puts it to sleep and wakes up another Goroutine, at which point it starts printing lots of zeros. The Goroutine is scheduled on the operating system thread at the time of printing.
On the second execution (runtime.gomaxprocs (2)), we use two cpus, so the two goroutines can be executed together, printing zeros and ones alternately at the same frequency.