Is there some elegant way to pause and resume any other goroutine?

后端 未结 2 2022
傲寒
傲寒 2021-01-31 21:06

In my case, I have thousands of goroutines working simultaneously as work(). I also had a sync() goroutine. When sync starts, I need any o

2条回答
  •  广开言路
    2021-01-31 22:00

    I edited jimt's excellent example to not loop around when it reaches default case and if state == Paused.

     65         default:
     66             fmt.Printf("Default case\n")
     67             if state == Paused {
     68                 fmt.Printf("Default state Paused\n")
     69                 select {
     70                     case state = <-ws:
     71                         switch state {
     72                         case Running:
     73                             fmt.Printf("Worker %d: Running\n", id)
     74                             break
     75                         case Stopped:
     76                             fmt.Printf("Worker %d: Stopped\n", id)
     77                             return
     78                         }
     79                     break
     80                 }
     81             }
     82             fmt.Printf("Do actual work here\n")
    

    An extra select+case, combination will be required to avoid a forever loop.

提交回复
热议问题