Home > Backend Development > Golang > How to synchronize Goroutines through Channels in Golang

How to synchronize Goroutines through Channels in Golang

PHPz
Release: 2023-08-15 08:17:06
Original
1079 people have browsed it

Golang 中 Goroutines 之间如何通过 Channels 进行同步

How to synchronize Goroutines in Golang through Channels

Goroutine is a lightweight thread in Golang that can execute multiple tasks in parallel in one program . In Goroutine, we can use Channels for data communication and synchronization. Channels provide a communication mechanism between Goroutines to ensure data correctness and synchronization.

In Golang, Channels are a type-safe element used to pass data between Goroutines. By using Channels, we can achieve synchronization between Goroutines to ensure that data is delivered and processed at the correct time and order.

Next, let’s look at a sample code to demonstrate how Goroutine synchronizes through Channels:

package main

import (
    "fmt"
    "time"
)

func worker(id int, jobs <-chan int, results chan<- int) {
    for j := range jobs {
        fmt.Println("Worker", id, "started job", j)
        time.Sleep(time.Second)
        fmt.Println("Worker", id, "finished job", j)
        results <- j * 2
    }
}

func main() {
    jobs := make(chan int, 100)
    results := make(chan int, 100)

    // 启动三个 Goroutine 执行任务
    for w := 1; w <= 3; w++ {
        go worker(w, jobs, results)
    }

    // 发送任务到 Jobs Channel
    for j := 1; j <= 5; j++ {
        jobs <- j
    }
    close(jobs)

    // 从 Results Channel 中接收结果
    for a := 1; a <= 5; a++ {
        <-results
    }

    time.Sleep(time.Second)
}
Copy after login

In the above example, we created two Channels: jobs and results. jobs is used to send tasks to Goroutine, and results is used to receive the results of task execution.

First, we started three Goroutines by using the go keyword and passed their required jobs and results Channels respectively. Then, we sent 5 tasks to the jobs Channel in a loop, and closed the jobs Channel when completed.

In the worker function, we use the range keyword to continuously receive tasks from the jobs Channel, and after processing the tasks Send the results to the results Channel. Since Channel is blocking, when we receive a task from jobs Channel, the Goroutine will stop and wait for the next task to arrive.

In the main function, we use the range keyword to continuously receive results from the results Channel. After the task is executed, we pass <-results expression to indicate that we want to receive result data, but we will not actually use these values.

Finally, in the main function, we use a delay function time.Sleep(time.Second) to ensure that the program does not terminate immediately after the Goroutine is executed.

Through the above sample code, we can see that by using Channels, we can achieve synchronization between Goroutines to ensure the correctness and order of data. In actual applications, we can create different types of Channels as needed to meet various needs.

To sum up, synchronization between Goroutines in Golang through Channels is a simple and powerful mechanism. It not only provides communication between threads, but also ensures the correctness and synchronization of data, providing convenience and flexibility for concurrent programming.

The above is the detailed content of How to synchronize Goroutines through Channels in Golang. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template