This is a creation in Article, where the information may have evolved or changed.
One project Main.gopackage mainimport ("FMT" "Runtime" "Sync") var counter int = 0func Count (lock *sync. Mutex) {//The lock is required before each pair of counter operations, and is unlocked after each use. Lock. Lock () counter++fmt. PRINTLN (counter) lock. Unlock ()}func main () {//Create a mutex structure under the sync package Lock: = &sync. Mutex{}for I: = 0; I < 10; i++ {go Count (lock)}for {lock. Lock () c: = Counterlock. Unlock () runtime. Gosched () If C > 0 {break}}}
Instead of communicating through shared memory, you should share memory through communication.
Use channel to implement just that example
Package Mainimport "FMT" func Count (ch Chan int) {FMT. Println ("Counting") Ch <-1}func Main () {CHS: = make ([]chan int, ten) for I: = 0; i <; i++ {chs[i] = make (chan int) g o Count (Chs[i])}for _, ch: = Range CHS {<-ch}}
One project Main.gopackage mainimport ("FMT") func main () {//channel declaration//var channame chan Elementtypevar Ch Chan int//A A map key for Channel//var m Map[string]chan bool//stringkey is of type bool use make to define a channel//ch1: = make (chan int)/* Writes a data to (sends) with Channelch <-value reads a data from the Channel value: = <-value*///select Statement Select {//if Chan1 successfully reads the data, Then the case processing statement is made <-chan1://if the data is successfully written to chan2, then the process is made in case chan2 <-1://If none of the above is successful, enter the default process DEFAULT:}CH2 : = Make (chan int) for {select {case ch <-0:case ch <-1:}i: = <-ch2fmt. Println ("value", I)}//buffering mechanism//Create a buffered CHANNELC: = Make (chan int, 1024)//use for range to read for I: = Range C {fmt. Println (i)}}