Skip to content

Instantly share code, notes, and snippets.

@bunyk
Last active March 2, 2018 12:11
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 bunyk/4ab1b5ab9dcade95b362c7625b311ec5 to your computer and use it in GitHub Desktop.
Save bunyk/4ab1b5ab9dcade95b362c7625b311ec5 to your computer and use it in GitHub Desktop.
Go concurrency examples
package main
import (
"fmt"
"time"
)
func sleepSort(array []int) []int {
rc := make(chan int)
postpone := func(v int) {
time.Sleep(time.Duration(v) * time.Millisecond)
rc <- v
}
max := 0
for _, v := range array {
go postpone(v)
if v > max {
max = v
}
}
res := make([]int, 0)
for {
v := <-rc
res = append(res, v)
if v == max {
return res
}
}
}
func main() {
fmt.Println(sleepSort([]int{43, 2, 3, 10, 22, -10, 7, 2, 3, 100, -1, -2}))
}
package main
import (
"fmt"
"sync"
"time"
)
func sleepSort(array []int) []int {
rc := make(chan int)
postpone := func(v int, wg *sync.WaitGroup) {
time.Sleep(time.Duration(v) * time.Millisecond)
rc <- v
wg.Done()
}
var wg sync.WaitGroup
max := 0
for _, v := range array {
wg.Add(1)
go postpone(v, &wg)
if v > max {
max = v
}
}
res := make([]int, 0)
go func() {
for {
v := <-rc
res = append(res, v)
}
}()
wg.Wait()
return res
}
func main() {
fmt.Println(sleepSort([]int{43, 2, 3, 10, 22, -10, 7, 2, 3, 100, -1, -2}))
}
package main
import (
"fmt"
//"math/rand"
"time"
)
func generator(c chan<- int) {
v := 0
for {
v++
time.Sleep(200 * time.Millisecond)
// v := rand.Intn(100)
fmt.Println("Generated", v)
c <- v
}
}
func worker(n int, in <-chan int, out chan<- int) {
for {
v := <-in
fmt.Println("worker", n, "got", v)
time.Sleep(5000 * time.Millisecond)
fmt.Println("worker", n, "processed", v)
out <- v
}
}
func reader(c <-chan int) {
for {
v := <-c
fmt.Println("Pull outputs", v)
}
}
func main() {
data := make(chan int, 10)
results := make(chan int, 10)
go generator(data)
for i := 0; i < 10; i++ {
go worker(i, data, results)
}
reader(results)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment