The sync Go packages
The sync
Go package contains functions that can help you synchronize goroutines; the most important functions of sync
are sync.Add
, sync.Done
, and sync.Wait
. The synchronization of goroutines is a mandatory task for every programmer.
Note that the synchronization of goroutines has nothing to do with shared variables and shared state. Shared variables and shared state have to do with the method you want to use for performing concurrent interactions.
A simple example
In this subsection, we will present a simple program that creates two goroutines. The name of the sample program will be aGoroutine.go
and will be presented in three parts; the first part is the following:
package main import ( "fmt" "time" ) func namedFunction() { time.Sleep(10000 * time.Microsecond) fmt.Println("Printing from namedFunction!") }
Apart from the expected package
and import
statements, you can see the implementation of a function named namedFunction()
that sleeps for a while...