Go (Golang) / Concurrency in Go

Synchronization

This tutorial will guide you through the Sync package in Go, teaching you how to synchronize goroutines effectively.

Tutorial 4 of 4 4 resources in this section

Section overview

4 resources

Explains how Go handles concurrency using Goroutines and Channels.

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!

Need Help Implementing This?

We build custom systems, plugins, and scalable infrastructure.

Discuss Your Project

Related topics

Keep learning with adjacent tracks.

View category

HTML

Learn the fundamental building blocks of the web using HTML.

Explore

CSS

Master CSS to style and format web pages effectively.

Explore

JavaScript

Learn JavaScript to add interactivity and dynamic behavior to web pages.

Explore

Python

Explore Python for web development, data analysis, and automation.

Explore

SQL

Learn SQL to manage and query relational databases.

Explore

PHP

Master PHP to build dynamic and secure web applications.

Explore

Popular tools

Helpful utilities for quick tasks.

Browse tools

JWT Decoder

Decode and validate JSON Web Tokens (JWT).

Use tool

JSON Formatter & Validator

Beautify, minify, and validate JSON data.

Use tool

Hex to Decimal Converter

Convert between hexadecimal and decimal values.

Use tool

JavaScript Minifier & Beautifier

Minify or beautify JavaScript code.

Use tool

Unit Converter

Convert between different measurement units.

Use tool

Latest articles

Fresh insights from the CodiWiki team.

Visit blog

AI in Drug Discovery: Accelerating Medical Breakthroughs

In the rapidly evolving landscape of healthcare and pharmaceuticals, Artificial Intelligence (AI) in drug dis…

Read article

AI in Retail: Personalized Shopping and Inventory Management

In the rapidly evolving retail landscape, the integration of Artificial Intelligence (AI) is revolutionizing …

Read article

AI in Public Safety: Predictive Policing and Crime Prevention

In the realm of public safety, the integration of Artificial Intelligence (AI) stands as a beacon of innovati…

Read article

AI in Mental Health: Assisting with Therapy and Diagnostics

In the realm of mental health, the integration of Artificial Intelligence (AI) stands as a beacon of hope and…

Read article

AI in Legal Compliance: Ensuring Regulatory Adherence

In an era where technology continually reshapes the boundaries of industries, Artificial Intelligence (AI) in…

Read article

Need help implementing this?

Get senior engineering support to ship it cleanly and on time.

Get Implementation Help