Synchronization

Tutorial 4 of 4

Tutorial: Synchronization in Go

1. Introduction

Welcome to our comprehensive tutorial about the synchronization of goroutines in Go. Our primary goal is to help you understand how the sync package in Go can be used to effectively synchronize goroutines.

By the end of this tutorial, you should be able to:

  • Understand the concept of synchronization in Go
  • Use the sync package to synchronize goroutines
  • Apply best practices when working with goroutines

Prerequisites

You will need a basic understanding of Go programming language. Familiarity with goroutines and channels in Go will also be helpful.

2. Step-by-Step Guide

Goroutines are lightweight threads managed by the Go runtime. They run in the same address space, and their execution can be synchronized using the sync package. This package provides basic synchronization primitives such as Mutexes and WaitGroups.

Mutex

A Mutex is a mutual exclusion lock. It is used to protect shared data from being simultaneously accessed by multiple goroutines.

WaitGroup

A WaitGroup is used to wait for a collection of goroutines to finish their execution. It's a more efficient and safer way to wait for goroutines as compared to using time.Sleep() function.

3. Code Examples

Example 1: Using Mutex

package main

import (
    "fmt"
    "sync"
)

var x  = 0

func increment(wg *sync.WaitGroup, m *sync.Mutex) {
    m.Lock()
    x = x + 1
    m.Unlock()
    wg.Done()   
}

func main() {
    var w sync.WaitGroup
    var m sync.Mutex

    for i := 0; i < 1000; i++ {
        w.Add(1)        
        go increment(&w, &m)
    }
    w.Wait()
    fmt.Println("final value of x", x)
}

In the above code:

  • We create a WaitGroup and a Mutex.
  • We start 1000 goroutines which all increment the shared variable x.
  • The Mutex is locked before the variable is incremented to prevent other goroutines from accessing it simultaneously.
  • Once the increment is done, the Mutex is unlocked and the WaitGroup is decremented.

Example 2: Using WaitGroup

package main

import (
    "fmt"
    "sync"
)

func process(i int, wg *sync.WaitGroup) {
    fmt.Println("started Goroutine ", i)
    wg.Done()
}

func main() {
    numOfGoroutines := 3
    var wg sync.WaitGroup

    for i := 0; i < numOfGoroutines; i++ {
        wg.Add(1)
        go process(i, &wg)
    }

    wg.Wait()
    fmt.Println("All go routines finished executing")
}

In the above code:

  • We define a function process that simulates a goroutine.
  • We create multiple goroutines in the main function.
  • We use wg.Done() to notify the WaitGroup that a goroutine has finished executing.
  • We call wg.Wait() to block until all goroutines have finished executing.

4. Summary

In this tutorial, we've learned about the use of Mutex and WaitGroup in the sync package of Go for synchronizing goroutines.

For further learning, check the official Go documentation (https://golang.org/pkg/sync/) and Effective Go (https://golang.org/doc/effective_go.html).

5. Practice Exercises

Exercise 1

Create a program with two goroutines. One goroutine should write data into a map, and the other should read data from the map. Use a Mutex to synchronize access to the map.

Exercise 2

Create a program that starts ten goroutines; each goroutine should print a message "Hello from goroutine X", where X is the goroutine number. Use a WaitGroup to ensure that the main function doesn't exit until all goroutines have finished executing.

Remember, the best way to learn is by doing. Happy coding!