Package Main;import ("FMT" "Runtime" "Sync")//goruntine to communicate to share memory, rather than shared memory for communication//channel is goruntine communication bridge, mostly blocking synchronization// Create by make, close close//channel is a reference type//use for range to iterate operations channel//can set a one-way or two-way channel//can set the cache size, does not occur before the blocking Func main () {// Here you need to set the type of Chan ch: = Make (chan bool); go func () {fmt. Println ("Run ..."); Ch <-true;} ();//This is blocked until the anonymous function is completed, the CH is set to TRUE//when the data is read out, it exits. <-ch;ch1: = Make (chan bool); go func () {fmt. Println ("Run ..."); Ch1 <-true;close (CH1);} ();//For Chan to iterate, the Chan must be closed somewhere else, or a deadlock for V will occur: = Range Ch1 {fmt. Println (v);} There is a cache that is asynchronous CH2: = Make (chan bool, 1); go func () {fmt. Println ("Run ..."); <-ch2;} (); CH2 <-true;//uses a multi-core runtime. Gomaxprocs (runtime. NUMCPU ()); CH3: = Make (chan bool, ten); for I: = 0; I < 10; i++ {Go run (CH3, i);} Read this here 10 times, with the above Go run () the same number of executions//guaranteed 10 runs are completed before exiting for i:= 0; I < 10; i++ {<-ch3;} Here you create the task wg: = Sync. WAITGROUP{};WG. ADD (ten); for I: = 0; I < 10; i++ {Go run2 (&WG, i);} Wait for all tasks to complete the WG. Wait ();//When there are multiple Chan, how to handle CH4, CH5: = make (chan int), "Make" (Chan string),//used to determine whether to close ch6: = Do (chan bool); go func () {for {select {case V, OK: = <-ch4:if!ok {ch6 <-true;break;} Fmt. Println (v); case V, OK: = <-ch5:if!ok {ch6 <-true;break;} Fmt. Println (v);}} (); CH4 <-1;ch4 <-2;ch5 <-"Hello"; Ch5 <-"World"; close (CH4); close (CH5);//loop read two times for i: = 0; I < 2; i++ {<-ch6;}} Func Run (CH chan bool, ix int) {A: = 0;for I: = 1; i < 10000; i++ {a + = i;} Fmt. Println (ix, a);//pass True to Chan, indicating that the run execution ends ch <-true; Func RUN2 (WG *sync. Waitgroup, ix int) {A: = 0;for I: = 1; i < 10000; i++ {a + = i;} Fmt. Println (ix, a);//Task Completion WG. Done ();}
Concurrency in the Go language