There is a worker program based on channels, that is, I indicate the number of workers (gorutin), say 16, perform the function, function is infinite, that is, it will be performed an infinite number of times in 16 Gorutin, you can stop only if you send a signal of completion *chan bool , but it does not work, I don’t want to start work at all, I suspect that the problem is to add

 var s string fmt.Scanln(&s) 

But then I need to forcibly press any of the buttons to complete the program or its actions, but I absolutely do not need it, tell me what my problem is. Here is the code:

 type st struct { workers int stop *chan bool } func main() { s := st{workers: 16} s.run() time.Sleep(2 *time.Second) s.pstop() } func (s *st) pstop() { for i := 0; i < s.workers; i++ { (*s.stop) <- true } close(*s.stop) } func (s *st) run() { schan := make(chan bool) s.stop = &schan for i := 0; i < s.workers; i++ { go func() { for { select { case <- (*s.stop): return default: fmt.Println("hello") } } }() } } 
  • It is not clear at what point the application should stop, but in general, if there is a need to wait for the execution of the gorutin, then sync.WaitGroup {} can be used - Evgeny Gavrilov
  • @ Yevgeny Gavrilov, so I, in the function main, declared that it was working for 2 seconds and after 2 seconds - stop, this should be done without waiting for the work of other gorutin to get everything as fast as possible, that is, you can force it. - Mothership
  • one
    There is no need to use a pointer to the channel, since the channel itself is already a reference type, like map and slice. - Ivan Black
  • one
    Everything works for me play.golang.org/p/jqpacjADJyy - Ivan Black
  • @IvanBlack thanks! And the truth works - Mothership

0