Jay Taylor's notes

back to listing index

Is there some elegant way to pause & resume any other goroutine in golang?

[web search]
Original source (stackoverflow.com)
Tags: examples golang go concurrency stackoverflow.com
Clipped on: 2015-03-10

In my case, I have thousands of goroutines working simultaneously as work(). I also had a sync() goroutine. When sync starts, I need any other goroutine to pause for a while after sync job is done. Here is my code:

var channels []chan int
var channels_mutex sync.Mutex

func work() {
  channel := make(chan int, 1)
  channels_mutex.Lock()  
  channels = append(channels, channel)
  channels_mutex.Unlock()
  for {
    for {
      sync_stat := <- channel // blocked here
      if sync_stat == 0 { // if sync complete
        break  
      }
    }
    // Do some jobs
    if (some condition) {
      return
    }
  }
}

func sync() {
  channels_mutex.Lock()
  // do some sync

  for int i := 0; i != len(channels); i++ {
    channels[i] <- 0
  }
  channels_mutex.Unlock()
}

Now the problem is, since <- is always blocking on read, every time goes to sync_stat := <- channel is blocking. I know if the channel was closed it won't be blocked, but since I have to use this channel until work() exits, and I didn't find any way to reopen a closed channel.

I suspect myself on a wrong way, so any help is appreciated. Is there some "elegant" way to pause & resume any other goroutine in golang?

Image (Asset 1/3) alt=