Skip to content

Instantly share code, notes, and snippets.

@saiumesh535
Created April 23, 2020 11:12
Show Gist options
  • Save saiumesh535/f129fea4141521695f41bf1005ccdbfc to your computer and use it in GitHub Desktop.
Save saiumesh535/f129fea4141521695f41bf1005ccdbfc to your computer and use it in GitHub Desktop.
go routines example
package main
import (
"fmt"
"math/rand"
"sync"
"time"
)
// fake version of DB
func connectDB(c chan int) {
fmt.Println("task_one_done")
time.Sleep(time.Second)
c <- 1
}
// fake redis
func connectRedis(c chan string) {
fmt.Println("task_two_done")
time.Sleep(time.Second)
c <- "done"
}
// fake file reader
func reader(target int, c chan string) {
time.Sleep(time.Second)
lol := fmt.Sprintf("Done for %d", target)
c <- lol
}
// channel to channel
func stream(targets []int, c chan string) {
ch := make(chan string)
for _, v := range targets {
go reader(v, ch)
}
for range targets {
c <- <- ch
}
close(ch)
close(c)
}
func doesSomething(result *[]string, wg *sync.WaitGroup, m *sync.Mutex) {
instance := fmt.Sprintf("%d", rand.Int())
time.Sleep(time.Second)
m.Lock()
// sync code in cn
// this piece of code will wait until go routines unlocks
*result = append(*result, instance)
m.Unlock()
wg.Done()
}
func fakeRunner(c chan int, data int) {
c <- data
}
func one(length []int, c chan int) {
intChan := make(chan int)
for _, v := range length {
go fakeRunner(intChan, v)
}
for range length {
c <- <- intChan
}
close(c)
}
func two(length []int, c chan int) {
intChan := make(chan int)
for _, v := range length {
go fakeRunner(intChan, v)
}
for range length {
c <- <- intChan
}
close(c)
}
// waiting for multiple go routines
func asyncChannel() {
oneCha := make(chan int)
twoChan := make(chan int)
oneLength := []int{1,2,3}
twoLength := []int{4,5,6,7}
go one(oneLength, oneCha)
go two(twoLength, twoChan)
for i := 0; i< len(oneLength) + len(twoLength); i++ {
// this select waits for both the channels at a time
select {
case data := <- oneCha: {
fmt.Println(data)
}
case data := <- twoChan: {
fmt.Println(data)
}
}
}
}
func main() {
duration := time.Now()
ch := make(chan int)
go connectDB(ch)
redisChan := make(chan string)
go connectRedis(redisChan)
lol := <- ch
rediResult := <- redisChan
targets :=[]int{1,2,3,4,5}
streamChan := make(chan string)
go stream(targets, streamChan)
for val := range streamChan {
fmt.Println(val)
}
names := []string{}
leng := 5
var wg sync.WaitGroup
var m sync.Mutex
for i := 0; i < leng; i++ {
wg.Add(1)
go doesSomething(&names, &wg, &m)
}
wg.Wait()
fmt.Println(names)
fmt.Println("hello!!", lol, rediResult)
fmt.Println("executed in ", time.Since(duration))
asyncChannel();
fmt.Println("it's done")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment