Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Concurrency example in Go
package main
import (
"log"
"time"
"sync"
)
// Loop 10 times, print every 1 second
func One(){
for i:=0; i<10; i++{
log.Println("---> One:", i)
time.Sleep(1 * time.Second)
}
}
// Loop 10 times, print every 2 seconds
func Two(){
for i:=0; i<10; i++{
log.Println("---> Two:", i)
time.Sleep(2 * time.Second)
}
}
// Run one at a time
func RunBlocking(){
log.Println("---> Run and block")
One()
Two()
}
// Run in concurrency
func RunConcurrency(){
var wg sync.WaitGroup
log.Println("---> Run in cuncurrency")
// Add 1 for this block
wg.Add(1)
go func(){
One()
// Decrease the counter by 1
wg.Done()
}()
// Add 1 for this block
wg.Add(1)
go func(){
Two()
// Decrease the counter by 1
wg.Done()
}()
wg.Wait()
}
func main(){
// RunBlocking()
RunConcurrency()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment