go - How to run multiple goroutines and collect results in the same order it runs -
i have following code has double-go routine structure:
package main import( "fmt" "math/rand" "time" "strconv" ) func main(){ outchan := make(chan string) i:=0;i<10;i++{ go testfun(i, outchan) } i:=0;i<10;i++{ := <-outchan fmt.println(a) } } func testfun(i int, outchan chan<- string){ outchan2 := make(chan int) time.sleep(time.millisecond*time.duration(int64(rand.intn(10)))) j:=0;j<10;j++ { go testfun2(j, outchan2) } tempstr := strconv.formatint(int64(i),10)+" - " j:=0;j<10;j++ { tempstr = tempstr + strconv.formatint(int64(<-outchan2),10) } outchan <- tempstr } func testfun2(j int, outchan2 chan<- int){ time.sleep(time.millisecond*time.duration(int64(rand.intn(10)))) outchan2 <- j }
the output expecting
0 - 0123456789 1 - 0123456789 2 - 0123456789 3 - 0123456789 4 - 0123456789 5 - 0123456789 6 - 0123456789 7 - 0123456789 8 - 0123456789 9 - 0123456789
but instead got this:
7 - 7980345261 6 - 4035897621 3 - 9047526831 9 - 4032861975 8 - 9570831624 5 - 3798021546 1 - 0985362471 0 - 1849276035 2 - 9572806143 4 - 5768032419
could show me how achieve output expecting? i'm newbie , please forgive me if solution obvious. i've been looking for days.
to give better idea. issue you're reading single channel values pushed onto channel in arbitrary order due time.sleep
calls. if want issue time.sleep
calls concurrently simulate concurrent long-running processes, you'll want make each goroutine write channel results.
this way can iterate across in-order list of results channels blocking until next channel can read (the same idea output queue in answer maintaining order in multi-threaded pipeline) here's reworked code name changes make things easier track:
package main import( "fmt" "math/rand" "time" "strconv" ) func main(){ var jobs []chan string := 0; i<10; i++{ job := make(chan string) jobs = append(jobs, job) go testfun(i, job) } _, result := range jobs { fmt.println(<-result) } } func testfun(i int, job chan<- string){ var innerjobs []chan int time.sleep(time.millisecond*time.duration(int64(rand.intn(10)))) j := 0; j<10; j++ { innerjob := make(chan int) innerjobs = append(innerjobs, innerjob) go testfun2(j, innerjob) } tempstr := strconv.formatint(int64(i),10)+" - " _, result := range innerjobs { tempstr = tempstr + strconv.formatint(int64(<-result),10) } job <- tempstr } func testfun2(j int, innerjob chan<- int){ time.sleep(time.millisecond*time.duration(int64(rand.intn(10)))) innerjob <- j }
Comments
Post a Comment