Mutual Exclusion of Concurrent Goroutines

后端 未结 4 2120
天命终不由人
天命终不由人 2020-12-18 13:56

In my code there are three concurrent routines. I try to give a brief overview of my code,

Routine 1 {
do something

*Send int to Routine 2
Send int to Routi         


        
4条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-18 14:51

    You could use sync.Mutex. For example everything between im.Lock() and im.Unlock() will exclude the other goroutine.

    package main
    
    import (
    "fmt"
    "sync"
    )
    
    func f1(wg *sync.WaitGroup, im *sync.Mutex, i *int) {
      for {
        im.Lock()
        (*i)++
        fmt.Printf("Go1: %d\n", *i)
        done := *i >= 10
        im.Unlock()
        if done {
          break
        }
      }
      wg.Done()
    }
    
    func f2(wg *sync.WaitGroup, im *sync.Mutex, i *int) {
      for {
        im.Lock()
        (*i)++
        fmt.Printf("Go2: %d\n", *i)
        done := *i >= 10
        im.Unlock()
        if done {
          break
        }
      }
      wg.Done()
    }
    
    func main() {
        var wg sync.WaitGroup
    
        var im sync.Mutex
        var i int
    
        wg.Add(2)
        go f1(&wg, &im, &i)
        go f2(&wg, &im, &i)
        wg.Wait()   
    
    }
    

提交回复
热议问题