Snippets of Go Code for Working with Concurrency using Goroutines

I'm learning Go and want some simple code examples that demonstrate concurrency using goroutines. Can you provide some snippets?

1 Answers

āœ“ Best Answer

šŸš€ Goroutine Basics in Go

Goroutines are lightweight, concurrent functions in Go. Here are some snippets to get you started:

Basic Goroutine Launch

This example shows how to launch a simple goroutine:

package main

import (
	"fmt"
	"time"
)

func printMessage(msg string) {
	fmt.Println(msg)
}

func main() {
	go printMessage("Hello from goroutine!")
	time.Sleep(time.Millisecond * 100)
	fmt.Println("Hello from main function!")
}

Explanation: The go keyword launches printMessage as a goroutine. time.Sleep is added to ensure the goroutine has time to execute before the main function exits.

šŸ¤ Synchronization with Channels

Channels are used to communicate and synchronize between goroutines.

Channel Communication

This snippet shows how to send and receive data using channels:

package main

import (
	"fmt"
)

func sendData(ch chan string) {
	ch <- "Data from goroutine"
}

func main() {
	ch := make(chan string)
	go sendData(ch)
	msg := <-ch
	fmt.Println(msg)
}

Explanation: A channel ch is created. The sendData goroutine sends a string to the channel, and the main function receives it.

šŸ”’ Preventing Race Conditions with Mutexes

Mutexes are used to protect shared resources from concurrent access.

Mutex Example

This example demonstrates how to use a mutex to protect a counter:

package main

import (
	"fmt"
	"sync"
	"time"
)

var counter int
var mutex sync.Mutex

func incrementCounter() {
	mutex.Lock()
	counter++
	mutex.Unlock()
}

func main() {
	var wg sync.WaitGroup

	for i := 0; i < 1000; i++ {
		wg.Add(1)
		go func() {
			defer wg.Done()
			incrementCounter()
		}()
	}

	wg.Wait()
	fmt.Println("Counter:", counter)
}

Explanation: The mutex.Lock() and mutex.Unlock() calls ensure that only one goroutine can access and modify the counter at a time, preventing race conditions. A WaitGroup is used to wait for all goroutines to complete.

ā±ļø Using WaitGroups

WaitGroups are used to wait for a collection of goroutines to finish.

WaitGroup Example

package main

import (
	"fmt"
	"sync"
	"time"
)

func worker(id int, wg *sync.WaitGroup) {
	defer wg.Done()
	fmt.Printf("Worker %d starting\n", id)
	time.Sleep(time.Second)
	fmt.Printf("Worker %d done\n", id)
}

func main() {
	var wg sync.WaitGroup

	for i := 1; i <= 3; i++ {
		wg.Add(1)
		go worker(i, &wg)
	}

	wg.Wait()
	fmt.Println("All workers done!")
}

Explanation: wg.Add(1) increments the counter for each goroutine. wg.Done() decrements the counter when a goroutine finishes. wg.Wait() blocks until the counter is zero.

Know the answer? Login to help.