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!
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) } }
On your first try:
On the second try:
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!