Middle+
How is multitasking implemented in Go?
sobes.tech AI
Answer from AI
Concurrency in Go is implemented using goroutines and channels.
Goroutines:
- Lightweight threads managed by the Go runtime.
- Created with the
gokeyword before a function call. - Use less memory compared to traditional OS threads.
- The Go scheduler manages their execution on available OS threads.
// Example of creating a goroutine
func myFunction() {
// some work
}
go myFunction() // Runs myFunction in a new goroutine
Channels:
- Typed conduits for data exchange between goroutines.
- Used for synchronization and communication.
- Created with the
make(chan Type)function. <-operators are used for sending and receiving data.
// Example of using a channel
messages := make(chan string) // Create a channel for strings
// Launch a goroutine to send a message
go func() {
messages <- "hello" // Send data into the channel
}()
// Receive data from the channel
msg := <-messages
Go Scheduler:
- A multithreaded scheduler that efficiently distributes goroutines across OS threads.
- Uses the M:N model (Many-to-Many): multiple goroutines (M) multiplexed onto fewer OS threads (N).
- Implements work-stealing technique, where idle OS threads can "steal" ready-to-run goroutines from others.
Synchronization:
- Besides channels, Go provides the standard
syncpackage for lower-level synchronization, such as mutexes (sync.Mutex), RWMutex (sync.RWMutex), and wait groups (sync.WaitGroup).
Key idea of Go for parallelism:
- "Do not communicate by sharing memory; instead, share memory by communicating." This means that the preferred way for goroutines to interact is through channels rather than sharing mutable data with explicit locking.