-
Notifications
You must be signed in to change notification settings - Fork 292
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Add example29: handle multiple Go channel
Signed-off-by: Bo-Yi Wu <[email protected]>
- Loading branch information
Showing
3 changed files
with
73 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,50 @@ | ||
package main | ||
|
||
import ( | ||
"errors" | ||
"fmt" | ||
"math/rand" | ||
"sync" | ||
"time" | ||
) | ||
|
||
func main() { | ||
outChan := make(chan int, 100) | ||
errChan := make(chan error) | ||
finishChan := make(chan struct{}) | ||
wg := sync.WaitGroup{} | ||
wg.Add(100) | ||
for i := 0; i < 100; i++ { | ||
go func(outChan chan<- int, errChan chan<- error, val int, wg *sync.WaitGroup) { | ||
defer wg.Done() | ||
time.Sleep(time.Duration(rand.Int31n(1000)) * time.Millisecond) | ||
fmt.Println("finished job id:", val) | ||
outChan <- val | ||
if val == 60 { | ||
errChan <- errors.New("error in 60") | ||
} | ||
|
||
}(outChan, errChan, i, &wg) | ||
} | ||
|
||
go func() { | ||
wg.Wait() | ||
fmt.Println("finish all job") | ||
close(finishChan) | ||
}() | ||
|
||
Loop: | ||
for { | ||
select { | ||
case val := <-outChan: | ||
fmt.Println("finished:", val) | ||
case err := <-errChan: | ||
fmt.Println("error:", err) | ||
break Loop | ||
case <-finishChan: | ||
break Loop | ||
case <-time.After(100000 * time.Millisecond): | ||
break Loop | ||
} | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,22 @@ | ||
package main | ||
|
||
import ( | ||
"fmt" | ||
"math/rand" | ||
"sync" | ||
"time" | ||
) | ||
|
||
func main() { | ||
wg := sync.WaitGroup{} | ||
wg.Add(100) | ||
for i := 0; i < 100; i++ { | ||
go func(val int, wg *sync.WaitGroup) { | ||
time.Sleep(time.Duration(rand.Int31n(1000)) * time.Millisecond) | ||
fmt.Println("finished job id:", val) | ||
wg.Done() | ||
}(i, &wg) | ||
} | ||
|
||
wg.Wait() | ||
} |