golang學習筆記[3] 並發編程

來源:互聯網
上載者:User
這是一個建立於 的文章,其中的資訊可能已經有所發展或是發生改變。



// one project main.gopackage mainimport ("fmt""runtime""sync")var counter int = 0func Count(lock *sync.Mutex) {//每次對counter操作前都需要加鎖,每次使用完之後都要解鎖。lock.Lock()counter++fmt.Println(counter)lock.Unlock()}func main() {//建立一個sync包下的Mutex結構體lock := &sync.Mutex{}for i := 0; i < 10; i++ {go Count(lock)}for {lock.Lock()c := counterlock.Unlock()runtime.Gosched()if c > 0 {break}}}



不要通過共用記憶體來通訊,而應該通過通訊來共用記憶體。


使用channel來實現剛剛那個例子


package mainimport "fmt"func Count(ch chan int) {fmt.Println("Counting")ch <- 1}func main() {chs := make([]chan int, 10)for i := 0; i < 10; i++ {chs[i] = make(chan int)go Count(chs[i])}for _, ch := range chs {<-ch}}



// one project main.gopackage mainimport ("fmt")func main() {//channel聲明// var chanName chan elementTypevar ch chan int//一個map鍵為stringkey為bool類型的channel//var m map[string]chan bool//使用make定義一個channel//ch1 := make(chan int)/*將一個資料寫入(發送)帶channelch <- value將一個資料從channel中讀出value := <- value*///select語句select {//如果chan1成功讀到資料,則進行該case處理語句case <-chan1://如果成功向chan2寫入資料,則進行該case處理語句case chan2 <- 1://如果上面都沒有成功,則進入default處理流程default:}ch2 := make(chan int)for {select {case ch <- 0:case ch <- 1:}i := <-ch2fmt.Println("value", i)}//緩衝機制//建立一個帶緩衝的channelc := make(chan int, 1024)//使用for range讀取for i := range c {fmt.Println(i)}}

















聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.