Golang learning notes [3] concurrent programming

Source: Internet
Author: User
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)}}

















Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.