Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
Some concurrency pattern inside
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(&notLast, 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(&notLast) == 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