Last active
October 25, 2016 18:26
-
-
Save mhmxs/302792bde11f6511391357056290e891 to your computer and use it in GitHub Desktop.
Some concurrency pattern inside
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" | |
"math" | |
"math/rand" | |
"sync" | |
"sync/atomic" | |
"time" | |
) | |
const ( | |
MAX = 500 | |
PRODUCERS = 12 | |
CONSUMERS = 9 | |
COUNTERS = 2 | |
) | |
func main() { | |
results := make([]int, 0) | |
mtx := new(sync.RWMutex) | |
// számláló | |
var itsLast, notLast int32 | |
countChan := make(chan int, COUNTERS) | |
counter := func() { | |
for { | |
e := <-countChan | |
mtx.RLock() | |
last := results[len(results)-1] | |
mtx.RUnlock() | |
if e != last { | |
atomic.AddInt32(¬Last, 1) | |
} else { | |
atomic.AddInt32(&itsLast, 1) | |
} | |
} | |
} | |
for i := 0; i < COUNTERS; i++ { | |
go counter() | |
} | |
// feldolgozó | |
appendChan := make(chan int, CONSUMERS) | |
cons := func() { | |
for { | |
e := <-appendChan | |
for i := 0; i < 500; i++ { | |
e = int(math.Min(float64(e), float64(rand.Int()))) | |
} | |
mtx.Lock() | |
results = append(results, e) | |
mtx.Unlock() | |
countChan <- e | |
} | |
} | |
for i := 0; i < CONSUMERS; i++ { | |
go cons() | |
} | |
// generátor | |
var start int64 | |
once := new(sync.Once) | |
poolChan := make(chan bool, PRODUCERS) | |
prod := func(wg *sync.WaitGroup) { | |
defer wg.Done() | |
once.Do(func() { start = time.Now().UnixNano() }) | |
e := rand.Int() | |
for i := 0; i < 999; i++ { | |
e = int(math.Min(float64(e), float64(rand.Int()))) | |
} | |
appendChan <- e | |
<-poolChan | |
} | |
wg := new(sync.WaitGroup) | |
wg.Add(MAX) | |
for i := 0; i < MAX; i++ { | |
poolChan <- true | |
go prod(wg) | |
} | |
wg.Wait() | |
var done bool | |
for !done { | |
done = atomic.LoadInt32(&itsLast)+atomic.LoadInt32(¬Last) == MAX | |
} | |
fmt.Printf("time spent: %dms\n", (time.Now().UnixNano()-start)/1000000) | |
fmt.Printf("last:not ratio: %d:%d\n", itsLast, notLast) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment