Last active
May 24, 2016 14:15
-
-
Save caike/9a124c7d17eec2d55f7a06fc5dda46f6 to your computer and use it in GitHub Desktop.
Concurrency example in Go
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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 | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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