Skip to content

Instantly share code, notes, and snippets.

@mhmxs
Last active October 25, 2016 18:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mhmxs/302792bde11f6511391357056290e891 to your computer and use it in GitHub Desktop.
Save mhmxs/302792bde11f6511391357056290e891 to your computer and use it in GitHub Desktop.
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