Skip to content

Instantly share code, notes, and snippets.

@kaneshin
Last active June 11, 2016 02:23
Show Gist options
  • Save kaneshin/0274fd2a35af5a9f8ba92e8f1c033e85 to your computer and use it in GitHub Desktop.
Save kaneshin/0274fd2a35af5a9f8ba92e8f1c033e85 to your computer and use it in GitHub Desktop.
package main
import (
"fmt"
"sync"
"time"
)
const (
maxConcurrency = 10
)
var (
concurrency = 0
mu = new(sync.RWMutex)
// Locker utility function
lockTx = func(mu sync.Locker, fn func(sync.Locker)) {
mu.Lock()
defer mu.Unlock()
fn(mu)
}
// Useful read only locker function
readLockTx = func(mu *sync.RWMutex, fn func(sync.Locker)) {
lockTx(mu.RLocker(), fn)
}
)
func process(wg *sync.WaitGroup, i int) {
lockTx(mu, func(locker sync.Locker) {
concurrency++
})
defer func() {
lockTx(mu, func(locker sync.Locker) {
concurrency--
})
wg.Done()
}()
readLockTx(mu, func(locker sync.Locker) {
fmt.Printf("%06d [%v] Concurrency %v\n", i, time.Now().Format(time.RFC3339), concurrency)
})
time.Sleep(1500 * time.Millisecond)
}
func main() {
now := time.Now()
defer func() {
fmt.Printf("Result:\n %f\n", float64((time.Now().UnixNano()-now.UnixNano()))/float64(time.Second))
}()
const n = 3000
for i := 0; i < n; i += maxConcurrency {
wg := new(sync.WaitGroup)
for j := 0; j < maxConcurrency; j++ {
wg.Add(1)
go process(wg, i+j)
}
wg.Wait()
}
}
@kaneshin
Copy link
Author

kaneshin commented Jun 11, 2016

Replace go process(wg, i+j) with process(wg, i+j) (just remove go!) if you confirm non-concurrent.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment