Sobes.tech
Junior — Middle

How does thread operation and synchronization work in Golang?

sobes.tech AI

Answer from AI

In Go, goroutines are lightweight threads managed by the Go runtime. They are launched with the go keyword before a function call, allowing asynchronous execution.

Synchronization of goroutines is achieved using channels and synchronization primitives from the sync package, such as Mutex and WaitGroup. Channels facilitate safe data exchange and synchronization between goroutines.

Example of using goroutines and channels:

package main

import (
    "fmt"
    "time"
)

func worker(ch chan string) {
    time.Sleep(time.Second)
    ch <- "done"
}

func main() {
    ch := make(chan string)
    go worker(ch)
    msg := <-ch
    fmt.Println("Goroutine work:", msg)
}

Here, the main goroutine launches worker in a separate goroutine, which sends a message to the channel after a delay. The main goroutine waits to receive the message, ensuring synchronization.

How does thread operation and synchronization work in… - sobes.tech