golang實現(xiàn)協(xié)程安全的幾種方式

  • 版本
    golang -- 1.12.4

  • golang協(xié)程同步

1.channel - monitor goroutine

var deposits = make(chan int) // send amount to deposit
var balances = make(chan int) // receive balance

func Deposit(amount int) { deposits <- amount }
func Balance() int       { return <-balances }

func teller() {
     var balance int // balance is confined to teller goroutine
     for {
         select {
         case amount := <-deposits:
              balance += amount
         case balances <- balance:
         }
      }
}
func init() {
     go teller() // start the monitor goroutine
}

2.channel - serial confinement

type Cake struct{ state string }

func baker(cooked chan<- *Cake) {
     for {
             cake := new(Cake)
             cake.state = "cooked"
             cooked <- cake // baker never touches this cake again
         } 
}

func icer(iced chan<- *Cake, cooked <-chan *Cake) {
      for cake := range cooked {
             cake.state = "iced"
             iced <- cake // icer never touches this cake again
      } 
}

3.mutual exclusion

import "sync"

var mu      sync.Mutex // guards balance
var balance int

func Deposit(amount int) {
         mu.Lock()
         balance = balance + amount
         mu.Unlock()
}

func Balance() int {
         mu.Lock()
         defer mu.Unlock()
         return balance
}

4.mutual exclusion - RWMutex

import "sync"

var mu      sync.RWMutex // guards balance
var balance int

func Deposit(amount int) {
         mu.Lock()
         balance = balance + amount
         mu.Unlock()
}

func Balance() int {
         mu.RLock() //readers lock
         defer mu.RUnlock()
         return balance
}

RLock允許讀取并行,寫入和讀取完全互斥,多次讀取,一次寫入

5.Lazy Initialization - sync.Once

var loadIconsOnce sync.Once
var icons map[string]image.Image
// Concurrency-safe.
func Icon(name string) image.Image {
     loadIconsOnce.Do(loadIcons)
     return icons[name]
}

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關(guān)閱讀更多精彩內(nèi)容

  • 介紹 如何保證在一個goroutine中看到在另一個goroutine修改的變量的值,這篇文章進行了詳細說明。 建...
    51reboot閱讀 19,998評論 11 41
  • Go(又稱Golang)是Google開發(fā)的一種靜態(tài)強類型、編譯型、并發(fā)型,并具有垃圾回收功能的編程語言。Go于2...
    臣以君綱閱讀 3,872評論 0 4
  • 開發(fā)go程序的時候,時常需要使用goroutine并發(fā)處理任務,有時候這些goroutine是相互獨立的,而有的時...
    駐馬聽雪閱讀 2,573評論 0 21
  • Go的內(nèi)存模型 看完這篇文章你會明白 一個Go程序在啟動時的執(zhí)行順序 并發(fā)的執(zhí)行順序 并發(fā)環(huán)境下如何保證數(shù)據(jù)的同步...
    初級賽亞人閱讀 2,967評論 0 2
  • 你有夢 我有夢 我們遇見了 你背棄 我受了 卻不曾想 你卻懇求回頭 我收了 卻不料想 你變了 那樣肆無忌憚 那樣痛...
    海市蜃樓你的眼閱讀 229評論 0 1

友情鏈接更多精彩內(nèi)容