How would you define a pool of goroutines to be executed at once?

I would spawn 4 worker goroutines that read the tasks from a common channel. Goroutines that are faster than others (because they are scheduled differently or happen to get simple tasks) will receive more task from this channel than others. In addition to that, I would use a sync.WaitGroup to wait for all workers to … Read more

Always have x number of goroutines running at any time

You may find Go Concurrency Patterns article interesting, especially Bounded parallelism section, it explains the exact pattern you need. You can use channel of empty structs as a limiting guard to control number of concurrent worker goroutines: package main import “fmt” func main() { maxGoroutines := 10 guard := make(chan struct{}, maxGoroutines) for i := … Read more

Is a Go goroutine a coroutine?

IMO, a coroutine implies supporting of explicit means for transferring control to another coroutine. That is, the programmer programs a coroutine in a way when they decide when a coroutine should suspend execution and pass its control to another coroutine (either by calling it or by returning/exiting (usually called yielding)). Go’s “goroutines” are another thing: … Read more

Max number of goroutines

If a goroutine is blocked, there is no cost involved other than: memory usage slower garbage-collection The costs (in terms of memory and average time to actually start executing a goroutine) are: Go 1.6.2 (April 2016) 32-bit x86 CPU (A10-7850K 4GHz) | Number of goroutines: 100000 | Per goroutine: | Memory: 4536.84 bytes | Time: … Read more

Multiple goroutines listening on one channel

Yes, it’s complicated, But there are a couple of rules of thumb that should make things feel much more straightforward. prefer using formal arguments for the channels you pass to go-routines instead of accessing channels in global scope. You can get more compiler checking this way, and better modularity too. avoid both reading and writing … Read more

Example for sync.WaitGroup correct?

Yes, this example is correct. It is important that the wg.Add() happens before the go statement to prevent race conditions. The following would also be correct: func main() { var wg sync.WaitGroup wg.Add(1) go dosomething(200, &wg) wg.Add(1) go dosomething(400, &wg) wg.Add(1) go dosomething(150, &wg) wg.Add(1) go dosomething(600, &wg) wg.Wait() fmt.Println(“Done”) } However, it is rather … Read more