Last active
June 11, 2016 02:23
-
-
Save kaneshin/0274fd2a35af5a9f8ba92e8f1c033e85 to your computer and use it in GitHub Desktop.
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
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() | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Replace
go process(wg, i+j)
withprocess(wg, i+j)
(just removego
!) if you confirm non-concurrent.