Javatpoint Logo
Javatpoint Logo

Go Mutex

Mutual Exclusion locks, or mutexes can be used to synchronize access to state and safely access data across many goroutines. It acts as a guard to the entrance of the critical section of code so that only one thread can enter the critical section at a time.

We set a lock around particular lines of code with it. While one Goroutine holds the lock, all other Goroutines are prevented from executing any lines of code protected by the same mutex, and are forced to wait until the lock is yielded before they can proceed.

Go Mutex Example


bar:  0 Count:  1
bar:  1 Count:  2
bar:  2 Count:  3
bar:  3 Count:  4
bar:  4 Count:  5
bar:  5 Count:  6
bar:  6 Count:  7
bar:  7 Count:  8
bar:  8 Count:  9
bar:  9 Count:  10
foo:  0 Count:  11
foo:  1 Count:  12
foo:  2 Count:  13
foo:  3 Count:  14
foo:  4 Count:  15
foo:  5 Count:  16
foo:  6 Count:  17
foo:  7 Count:  18
foo:  8 Count:  19
foo:  9 Count:  20
last count value  20

Next TopicGo Atomic Variable

Youtube For Videos Join Our Youtube Channel: Join Now


Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials


Trending Technologies

B.Tech / MCA