Sobes.tech
Senior

What is a semaphore?

sobes.tech AI

Answer from AI

A semaphore is a primitive synchronization tool used to control access to a shared resource in multithreaded or concurrent systems. It contains a counter that indicates how many threads can access the resource simultaneously.

Working principle:

  • When a thread wants to access, it attempts to "acquire" the semaphore. If the counter is greater than zero, it decreases by 1, and the thread continues.
  • If the counter is zero, the thread is blocked and waits until another thread releases the semaphore.
  • When a thread finishes with the resource, it "releases" the semaphore, increasing the counter by 1.

In Go, semaphores can be implemented using channels or third-party libraries.

Example of a simple semaphore in Go using a channel:

package main

import (
    "fmt"
    "time"
)

func worker(id int, sem chan struct{}) {
    sem <- struct{}{} // acquire semaphore
    fmt.Printf("Worker %d started\n", id)
    time.Sleep(time.Second) // work
    fmt.Printf("Worker %d finished\n", id)
    <-sem // release semaphore
}

func main() {
    sem := make(chan struct{}, 3) // semaphore with a maximum capacity of 3

    for i := 1; i <= 5; i++ {
        go worker(i, sem)
    }

    time.Sleep(5 * time.Second)
}

In this example, no more than 3 goroutines can work simultaneously.

What is a semaphore? — Golang - sobes.tech