SoFunction
Updated on 2025-03-02

Go handles interaction between threads sample code

In Go, the following methods are used to process interactions between threads (called "goroutines"):

1. Use Channels

Channels are the main mechanism in Go for communication between goroutines. With channels, you can safely pass data between different goroutines.

Sample code

package main
import (
    "fmt"
    "time"
)
func main() {
    // Create a channel    ch := make(chan string)
    // Start a goroutine    go func() {
        (1 * ) // Simulate some work        ch <- "Hello from goroutine!" // Send data to channel    }()
    // main goroutine waits and receives data    msg := <-ch
    (msg)
}

2. Use WaitGroup

Used to wait for a set of goroutines to complete. It provides an easy way to manage synchronization of concurrent tasks.

Sample code

package main
import (
    "fmt"
    "sync"
)
func main() {
    var wg 
    for i := 0; i < 3; i++ {
        (1) // Increasing the count        go func(i int) {
            defer () // Decrease count            ("Goroutine %d\n", i)
        }(i)
    }
    () // Wait for all goroutines to complete    ("All goroutines finished!")
}

3. Use Mutex

You can use it when multiple goroutines need to access shared datato ensure mutually exclusive access and prevent data competition.

Sample code

package main
import (
    "fmt"
    "sync"
)
var (
    counter int
    mu      
)
func increment(wg *) {
    defer ()
    ()         // Add lock    counter++         // Access shared data    ()       // Unlock}
func main() {
    var wg 
    for i := 0; i < 10; i++ {
        (1)
        go increment(&wg)
    }
    ()
    ("Final counter:", counter)
}

4. Use Select

selectStatements can wait for operations on multiple channels. It allows you to make more complex decisions while multiple goroutines communicate.

Sample code

package main
import (
    "fmt"
    "time"
)
func main() {
    ch1 := make(chan string)
    ch2 := make(chan string)
    go func() {
        (2 * )
        ch1 <- "Message from channel 1"
    }()
    go func() {
        (1 * )
        ch2 <- "Message from channel 2"
    }()
    select {
    case msg1 := <-ch1:
        (msg1)
    case msg2 := <-ch2:
        (msg2)
    }
}

Summarize

  • Channels: Used for secure communication between goroutines.
  • WaitGroup: Used to wait for multiple goroutines to complete.
  • Mutex: Used to protect access to shared data and prevent data competition.
  • Select: Used to handle the reception and transmission of multiple channels.

With the above methods, you can effectively handle interactions and synchronization between goroutines.

This is the end of this article about how Go handles interactions between threads. For more information about interactions between go threads, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!