In this example we’ll look at how to implement a worker pool using goroutines and channels. |
|
|
|
|
|
Here’s the worker, of which we’ll run several
concurrent instances. These workers will receive
work on the |
|
|
|
In order to use our pool of workers we need to send them work and collect their results. We make 2 channels for this. |
|
This starts up 3 workers, initially blocked because there are no jobs yet. |
|
Here we send 5 |
|
Finally we collect all the results of the work. This also ensures that the worker goroutines have finished. An alternative way to wait for multiple goroutines is to use a WaitGroup. |
|
Наша програма покаже 5 завдань - що виконуються різними працівниками. Програма працює близько 2 секунд, не зважаючи на роботу розраховану вцілому на 5 секунд - і все це завдяки 3’ом працівникам, що працюються одночасно. |
|
|
Наступний приклад: Групи Очікування (WaitGroups).