Skip to content

Instantly share code, notes, and snippets.

@bash0C7
Last active December 27, 2015 20:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bash0C7/7387774 to your computer and use it in GitHub Desktop.
Save bash0C7/7387774 to your computer and use it in GitHub Desktop.
Gorutine Training
package main
import "fmt"
import "time"
import "os"
import "flag"
func main() {
buffer_size := func() int {
b := 0
flag.IntVar(&b, "buffer_size", 0, "buffer_size")
flag.Parse()
return b
}()
doit("html", "urlstring", buffer_size)
}
func doit(format string, url string, buffer_size int) {
fmt.Println("start of doit")
source := make(chan string, buffer_size)
post_done := make(chan int)
source_count := prepair_source(source, url)
go post(post_done, source)
exit_if(func() bool {
fmt.Println(" #start of exit_if block")
posted_count := 0
for {
posted_count = posted_count + <-post_done
if source_count <= posted_count {
break
}
}
fmt.Println(" #end of set exit_if block")
return true
})
fmt.Println("end of doit")
}
func post(post_done chan int, source chan string) {
fmt.Println(" !start of post")
for {
time.Sleep(time.Second + time.Second)
fmt.Println(" !start of for")
fmt.Println(" !post! " + <-source)
fmt.Println(" !end of for")
post_done <- 1
}
fmt.Println(" !end of post")
}
func prepair_source(source chan string, url string) int {
fmt.Println(" @start of prepair_source")
go func() {
fmt.Println(" @start of gorutine in prepair_source")
fmt.Println(" @set url1")
source <- url + "1"
time.Sleep(time.Second)
fmt.Println(" @set url2")
source <- url + "2"
time.Sleep(time.Second)
fmt.Println(" @set url3")
source <- url + "3"
fmt.Println(" @end of gorutine in prepair_source")
}()
fmt.Println(" @end of set prepair_source")
return 3
}
func exit_if(condition func() bool) {
if condition() {
fmt.Println("EXIT!!!!!!!!!!")
os.Exit(0)
}
}
## チャネルのバッファが3=読み込み全部バッファに入る数
````sh
go run gorutine_training.go -buffer_size 3
````
````
start of doit
@start of prepair_source
@end of set prepair_source
@start of gorutine in prepair_source
#start of exit_if block
@set url1
!start of post
@set url2
!start of for
!post! urlstring1
!end of for
@set url3
@end of gorutine in prepair_source
!start of for
!post! urlstring2
!end of for
!start of for
!post! urlstring3
!end of for
#end of set exit_if block
EXIT!!!!!!!!!!
````
## チャネルのバッファがゼロ=実質シーケンシャルな動き
````sh
go run gorutine_training.go -buffer_size 0
````
````
start of doit
@start of prepair_source
@end of set prepair_source
@start of gorutine in prepair_source
#start of exit_if block
@set url1
!start of post
!start of for
!post! urlstring1
!end of for
@set url2
!start of for
!post! urlstring2
!end of for
@set url3
!start of for
!post! urlstring3
@end of gorutine in prepair_source
!end of for
#end of set exit_if block
EXIT!!!!!!!!!!
````
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment