Write chan in sync.WaitGroup goroutine
php editor Youzi will introduce a method of writing chan in sync.WaitGroup goroutine. In concurrent programming, sync.WaitGroup is a very useful synchronization mechanism that can wait for the execution of a group of goroutines to complete. However, sometimes we need to write the results to a chan after the goroutine completes execution for consumption by other goroutines. This article will introduce in detail how to implement this function in sync.WaitGroup goroutine, let's take a look!
Question content
I am getting a list of items from an API endpoint. Then, for each project, I make another API request to get data about the individual project.
I can't make a second API request to each project at the same time because my API token is rate limited and if I make too many requests at the same time I get throttled.
However, the initial API response data can be split into multiple pages, which allows me to process pages of data simultaneously.
After some research, the following code does exactly what I want:
func main() { // pretend paginated results from initial API request page1 := []int{1, 2, 3} page2 := []int{4, 5, 6} page3 := []int{7, 8, 9} pages := [][]int{page1, page2, page3} results := make(chan string) var wg sync.WaitGroup for i := range pages { wg.Add(1) go func(i int) { defer wg.Done() for j := range pages[i] { // simulate making additional API request and building the report time.Sleep(500 * time.Millisecond) result := fmt.Sprintf("Finished creating report for %d", pages[i][j]) results <- result } }(i) } go func() { wg.Wait() close(results) }() for result := range results { fmt.Println(result) } }
I want to understand why it works:
go func() { wg.Wait() close(results) }()
My first attempt was unsuccessful - I thought I could iterate over the channel after wg.Wait()
and I would read the results as they are written to the results
channel Get the result.
func main() { // pretend paginated results from initial API request page1 := []int{1, 2, 3} page2 := []int{4, 5, 6} page3 := []int{7, 8, 9} pages := [][]int{page1, page2, page3} results := make(chan string) var wg sync.WaitGroup for i := range pages { wg.Add(1) go func(i int) { defer wg.Done() for j := range pages[i] { // simulate making additional API request and building the report time.Sleep(500 * time.Millisecond) result := fmt.Sprintf("Finished creating report for %d", pages[i][j]) results <- result } }(i) } // does not work wg.Wait() close(results) for result := range results { fmt.Println(result) } }
Workaround
On your first try:
- The main goroutine causes 3 goroutines to put values into the result channel.
- The main coroutine waits for all coroutines to complete.
- One of the goroutines puts a value into the result channel and fills the channel (channel size is 1 string).
- Now all three goroutines can no longer put values into the result channel and go to sleep until the result channel is released.
- All goroutines are in sleep state. You're at an impasse.
On the second try:
- The main goroutine contains 4 goroutines.
- 3 goroutines put values into the result channel.
- The other goroutine (I'll call it the 4th one) waits for these 3 goroutines to finish.
- At the same time, the main coroutine waits for the value in the result channel (for loop)
- In this case, if one of the goroutines puts a value in the result channel, it will block the remaining three goroutines; the main Goroutine will take the value out of the result channel, thereby unblocking the other Goroutines.
- So, all 3 goroutines put their respective values and end
- Then the fourth goroutine closes the channel
- The main Goroutine ends its for loop.
The above is the detailed content of Write chan in sync.WaitGroup goroutine. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

There is a parent-child relationship between functions and goroutines in Go. The parent goroutine creates the child goroutine, and the child goroutine can access the variables of the parent goroutine but not vice versa. Create a child goroutine using the go keyword, and the child goroutine is executed through an anonymous function or a named function. A parent goroutine can wait for child goroutines to complete via sync.WaitGroup to ensure that the program does not exit before all child goroutines have completed.

Functions are used to perform tasks sequentially and are simple and easy to use, but they have problems with blocking and resource constraints. Goroutine is a lightweight thread that executes tasks concurrently. It has high concurrency, scalability, and event processing capabilities, but it is complex to use, expensive, and difficult to debug. In actual combat, Goroutine usually has better performance than functions when performing concurrent tasks.

In a multi-threaded environment, the behavior of PHP functions depends on their type: Normal functions: thread-safe, can be executed concurrently. Functions that modify global variables: unsafe, need to use synchronization mechanism. File operation function: unsafe, need to use synchronization mechanism to coordinate access. Database operation function: Unsafe, database system mechanism needs to be used to prevent conflicts.

Methods for inter-thread communication in C++ include: shared memory, synchronization mechanisms (mutex locks, condition variables), pipes, and message queues. For example, use a mutex lock to protect a shared counter: declare a mutex lock (m) and a shared variable (counter); each thread updates the counter by locking (lock_guard); ensure that only one thread updates the counter at a time to prevent race conditions.

The C++ concurrent programming framework features the following options: lightweight threads (std::thread); thread-safe Boost concurrency containers and algorithms; OpenMP for shared memory multiprocessors; high-performance ThreadBuildingBlocks (TBB); cross-platform C++ concurrency interaction Operation library (cpp-Concur).

The volatile keyword is used to modify variables to ensure that all threads can see the latest value of the variable and to ensure that modification of the variable is an uninterruptible operation. Main application scenarios include multi-threaded shared variables, memory barriers and concurrent programming. However, it should be noted that volatile does not guarantee thread safety and may reduce performance. It should only be used when absolutely necessary.

Function locks and synchronization mechanisms in C++ concurrent programming are used to manage concurrent access to data in a multi-threaded environment and prevent data competition. The main mechanisms include: Mutex (Mutex): a low-level synchronization primitive that ensures that only one thread accesses the critical section at a time. Condition variable (ConditionVariable): allows threads to wait for conditions to be met and provides inter-thread communication. Atomic operation: Single instruction operation, ensuring single-threaded update of variables or data to prevent conflicts.

Program performance optimization methods include: Algorithm optimization: Choose an algorithm with lower time complexity and reduce loops and conditional statements. Data structure selection: Select appropriate data structures based on data access patterns, such as lookup trees and hash tables. Memory optimization: avoid creating unnecessary objects, release memory that is no longer used, and use memory pool technology. Thread optimization: identify tasks that can be parallelized and optimize the thread synchronization mechanism. Database optimization: Create indexes to speed up data retrieval, optimize query statements, and use cache or NoSQL databases to improve performance.
