From: sgf Date: Tue, 31 May 2022 13:40:33 +0000 (+0300) Subject: new(go): Add video "Google I/O 2012 - Go Concurrency Patterns" and some code from it. X-Git-Url: https://gitweb.sgf-dma.tk/?a=commitdiff_plain;h=7bcd38903849aef175ec85e8c8ff3d68b414007c;p=go.git new(go): Add video "Google I/O 2012 - Go Concurrency Patterns" and some code from it. --- diff --git a/go-concurrency-patterns/.gitignore b/go-concurrency-patterns/.gitignore new file mode 100644 index 0000000..e9e5b3f --- /dev/null +++ b/go-concurrency-patterns/.gitignore @@ -0,0 +1 @@ +conc1 diff --git a/go-concurrency-patterns/Google_IO_2012_-_Go_Concurrency_Patterns-Rob_Pike-f6kdp27TYZs.webm b/go-concurrency-patterns/Google_IO_2012_-_Go_Concurrency_Patterns-Rob_Pike-f6kdp27TYZs.webm new file mode 120000 index 0000000..1b3a1a0 --- /dev/null +++ b/go-concurrency-patterns/Google_IO_2012_-_Go_Concurrency_Patterns-Rob_Pike-f6kdp27TYZs.webm @@ -0,0 +1 @@ +../.git/annex/objects/zW/j0/SHA256E-s427452422--4a49f19882b027b5db671084c06a574a6a05f41b8a9e285856fb3f1f76e00a8b.webm/SHA256E-s427452422--4a49f19882b027b5db671084c06a574a6a05f41b8a9e285856fb3f1f76e00a8b.webm \ No newline at end of file diff --git a/go-concurrency-patterns/conc1.go b/go-concurrency-patterns/conc1.go new file mode 100644 index 0000000..82f4a73 --- /dev/null +++ b/go-concurrency-patterns/conc1.go @@ -0,0 +1,59 @@ + +package main + +import ( + "fmt" + "time" + "math/rand" +) + +func boring(msg string) <- chan string { + c := make(chan string) + go func() { + for i := 0; ; i++ { + r := rand.Intn(3e3) + c <- fmt.Sprintf("%s %d (%d)", msg, i, r) + time.Sleep(time.Duration(r) * time.Millisecond) + } + }() + return c +} + +func main1() { + c := boring("boring!") + for i := 0; i< 5; i++ { + fmt.Printf("You say: %q\n", <-c) + } + fmt.Println("You're boring. I'm leaving.") +} + +func main2() { + joe := boring("Joe") + ann := boring("Ann") + for i := 0; i < 5; i++ { + fmt.Println(<-joe) + fmt.Println(<-ann) + } + fmt.Println("You're both boring. I'm leaving.") +} + +func fanIn(input1, input2 <- chan string) <-chan string { + c := make(chan string) + go func() { for { c <- <-input1 } }() + go func() { for { c <- <-input2 } }() + return c +} + +func main3() { + c := fanIn(boring("Joe"), boring("Ann")) + for i := 0; i < 10; i++ { + fmt.Printf("%q\n", <-c) + } + fmt.Println("You're boring. I'm leaving.") +} + +func main() { + rand.Seed(time.Now().Unix()) + + main3() +}