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!

Effective Go application error logging requires balancing details and performance. 1) Using standard log packages is simple but lacks context. 2) logrus provides structured logs and custom fields. 3) Zap combines performance and structured logs, but requires more settings. A complete error logging system should include error enrichment, log level, centralized logging, performance considerations, and error handling modes.

EmptyinterfacesinGoareinterfaceswithnomethods,representinganyvalue,andshouldbeusedwhenhandlingunknowndatatypes.1)Theyofferflexibilityforgenericdataprocessing,asseeninthefmtpackage.2)Usethemcautiouslyduetopotentiallossoftypesafetyandperformanceissues,

Go'sconcurrencymodelisuniqueduetoitsuseofgoroutinesandchannels,offeringalightweightandefficientapproachcomparedtothread-basedmodelsinlanguageslikeJava,Python,andRust.1)Go'sgoroutinesaremanagedbytheruntime,allowingthousandstorunconcurrentlywithminimal

Go'sconcurrencymodelusesgoroutinesandchannelstomanageconcurrentprogrammingeffectively.1)Goroutinesarelightweightthreadsthatalloweasyparallelizationoftasks,enhancingperformance.2)Channelsfacilitatesafedataexchangebetweengoroutines,crucialforsynchroniz

InterfacesandpolymorphisminGoenhancecodereusabilityandmaintainability.1)Defineinterfacesattherightabstractionlevel.2)Useinterfacesfordependencyinjection.3)Profilecodetomanageperformanceimpacts.

TheinitfunctioninGorunsautomaticallybeforethemainfunctiontoinitializepackagesandsetuptheenvironment.It'susefulforsettingupglobalvariables,resources,andperformingone-timesetuptasksacrossanypackage.Here'showitworks:1)Itcanbeusedinanypackage,notjusttheo

Interface combinations build complex abstractions in Go programming by breaking down functions into small, focused interfaces. 1) Define Reader, Writer and Closer interfaces. 2) Create complex types such as File and NetworkStream by combining these interfaces. 3) Use ProcessData function to show how to handle these combined interfaces. This approach enhances code flexibility, testability, and reusability, but care should be taken to avoid excessive fragmentation and combinatorial complexity.

InitfunctionsinGoareautomaticallycalledbeforethemainfunctionandareusefulforsetupbutcomewithchallenges.1)Executionorder:Multipleinitfunctionsrunindefinitionorder,whichcancauseissuesiftheydependoneachother.2)Testing:Initfunctionsmayinterferewithtests,b


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

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

Atom editor mac version download
The most popular open source editor

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Zend Studio 13.0.1
Powerful PHP integrated development environment

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function
