Skip to content

Instantly share code, notes, and snippets.

@cftang0827
Created January 23, 2020 07:15
Show Gist options
  • Save cftang0827/bd199bf566ac88401b382931217fb192 to your computer and use it in GitHub Desktop.
Save cftang0827/bd199bf566ac88401b382931217fb192 to your computer and use it in GitHub Desktop.
package main
import (
"fmt"
"math/rand"
"sync"
"time"
)
var sumPool int
var mutex = &sync.Mutex{}
var channel = make(chan (int))
func main() {
all := 1000
fmt.Println("Init value of sumPool :", sumPool)
t1 := time.Now().Nanosecond()
// fmt.Println(t1)
for i := 0; i < all; i++ {
go add()
}
for i := 0; i < all; i++ {
<-channel
}
fmt.Println("After value of sumPool :", sumPool)
t2 := time.Now().Nanosecond()
fmt.Printf("Time elapsed: %f msec\n", float32(t2-t1)/1000000.0)
}
func add() {
s1 := rand.NewSource(time.Now().UnixNano())
r1 := rand.New(s1)
time.Sleep(time.Duration(r1.Intn(10)) * time.Millisecond)
mutex.Lock()
sumPool++
mutex.Unlock()
channel <- 1
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment