Checking completion
The preceding example technically works, but depending on a timer to wait for threads to complete isn't reliable. If the threads need to wait for a response or are part way through a long calculation, we'll still have potential corruption if the timer elapses. The solution is to have the goroutine signal once the cleanup is complete. This can be done with sync.WaitGroup or by using another channel.
For our completed thread example, we create sync.WaitGroup, which is passed to each of the tick threads. Before we start the goroutine, we increment the number of threads to wait on using wg.Add(1). Once each thread is complete, they mark that using wg.Done(). Our application is then free to call wg.Wait() immediately before ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access