Last active
November 21, 2016 01:16
-
-
Save nametake/2d7a3a3b41f10e576c8799dd92f394e6 to your computer and use it in GitHub Desktop.
Goの複数スレッドを制御するための一案
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
package main | |
import ( | |
"context" | |
"fmt" | |
"strings" | |
"time" | |
) | |
const SLEEP_SEC = 0 | |
type SampleRunner struct { | |
identifier string | |
} | |
func (r *SampleRunner) Run(ctx context.Context, in <-chan int, out chan<- int) { | |
for { | |
select { | |
case <-ctx.Done(): | |
for { | |
select { | |
case v, ok := <-in: | |
if !ok { | |
close(out) | |
return | |
} | |
time.Sleep(SLEEP_SEC * time.Second) | |
fmt.Println(strings.Repeat("\t", v), r.identifier, "Done:", v) | |
out <- v | |
} | |
} | |
case v, ok := <-in: | |
if !ok { | |
close(out) | |
return | |
} | |
time.Sleep(SLEEP_SEC * time.Second) | |
fmt.Println(strings.Repeat("\t", v), r.identifier, ":", v) | |
out <- v | |
} | |
} | |
} | |
func main() { | |
ctx, cancel := context.WithCancel(context.Background()) | |
ch1 := make(chan int) | |
ch2 := make(chan int) | |
ch3 := make(chan int) | |
ch4 := make(chan int) | |
ch5 := make(chan int) | |
ch6 := make(chan int) | |
ch7 := make(chan int) | |
ch8 := make(chan int) | |
s1 := &SampleRunner{identifier: "sample1"} | |
s2 := &SampleRunner{identifier: "sample2"} | |
s3 := &SampleRunner{identifier: "sample3"} | |
s4 := &SampleRunner{identifier: "sample4"} | |
s5 := &SampleRunner{identifier: "sample5"} | |
s6 := &SampleRunner{identifier: "sample6"} | |
s7 := &SampleRunner{identifier: "sample7"} | |
go s1.Run(ctx, ch1, ch2) | |
go s2.Run(ctx, ch2, ch3) | |
go s3.Run(ctx, ch3, ch4) | |
go s4.Run(ctx, ch4, ch5) | |
go s5.Run(ctx, ch5, ch6) | |
go s6.Run(ctx, ch6, ch7) | |
go s7.Run(ctx, ch7, ch8) | |
go func() { | |
for i := 0; i < 10; i++ { | |
fmt.Println(strings.Repeat("\t", i), "input :", i) | |
ch1 <- i | |
} | |
close(ch1) | |
cancel() | |
}() | |
for { | |
select { | |
case v, ok := <-ch8: | |
if !ok { | |
return | |
} | |
fmt.Println(strings.Repeat("\t", v), "output :", v) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment