This is a creation in Article, where the information may have evolved or changed.
- Add the keyword go before a function call, this time the call will be executed in a new Goroutine (lightweight thread, coprocessor), and when the called function returns, the Goroutine ends, and if the function has a return value, the return value will be discarded.
- Lock mechanism and channel in go language
Package Mainimport ("FMT" "Sync" "Runtime") var counter int = 0func Count (lock *sync. Mutex) {lock. Lock () counter ++fmt. PRINTLN (counter) lock. Unlock ()}func main () {lock: = &sync. Mutex{}for I: = 0; I < 10; i + + {go Count (lock)}for {lock. Lock () c: = Counterlock. Unlock () runtime. Gosched () if C >= {break}}}
Package Mainimport ("FMT") func Count (ch Chan int) {FMT. Println ("Counting") Ch <-1}func Main () {CHS: = make ([]chan int, ten) for I: = 0; I < 10;i + + {Chs[i] = make (chan int) g o Count (Chs[i])}for _, ch: = Range (CHS) {<-ch}}
- Channel Declaration method
- Writing data to the channel
Ch <-val
- Read the data from the channel
Val: = <-Ch
- Select usage
Select { case <-chan1: ///If Chan1 successfully read the data, then make the process of the processing statement case chan2 <-1: //If the data is successfully written to Chan2, The case processing statement is default: //If none of the above is successful, then the default process is entered}
- Close the channel to determine if the channel is closed
Close the channel, directly using the go built-in close (CH) to determine if the channel is closed, using multiple return value mode x, OK: = <-ch
- Runtime. The Gosched () method is used to assign time slices, runtime. NUMCPU () is used to obtain the CPU core number, runtime. Gomaxprocs (16) Set the number of CPU cores that the routine uses
- Global uniqueness operation of sync. Once.do (func)