Create a gist now

Instantly share code, notes, and snippets.

@caike /a-main.go
Last active May 24, 2016

What would you like to do?
Concurrency example in Go
// Manual Semaphore
package main
import (
"fmt"
"time"
)
func main() {
startTime := time.Now().Unix()
isFinished := false
// Remember arguments are passed by value ?
// Let's pass it by reference here
go sleepTime(&isFinished)
for(!isFinished){
fmt.Println(time.Now().Unix())
}
endTime := time.Now().Unix()
duration := endTime - startTime
fmt.Println("Done in", duration, "seconds, from ", startTime, "until", endTime)
}
func sleepTime(isFinished *bool) {
time.Sleep(2 * time.Second)
*isFinished = true
}
// Using sync package
package main
import (
"fmt"
"sync"
"time"
)
func main() {
var wg sync.WaitGroup
wg.Add(1)
startTime := time.Now().Unix()
go sleepTime(&wg)
wg.Wait()
endTime := time.Now().Unix()
duration := endTime - startTime
fmt.Println("Done in", duration, "seconds, from ", startTime, "until", endTime)
}
func sleepTime(wg *sync.WaitGroup) {
time.Sleep(2 * time.Second)
wg.Done()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment