Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package main
- import (
- "math/rand"
- "sync"
- "time"
- )
- type Config struct {
- repMutex *sync.Mutex
- function func(int) int
- input1 <-chan int
- input2 <-chan int
- output chan int
- count int
- repository []int
- wg *sync.WaitGroup
- }
- func calc(config *Config, x1 int, x2 int, i int) {
- config.wg.Add(1)
- config.repMutex.Lock()
- config.repository[i] = config.function(x1) + config.function(x2)
- config.repMutex.Unlock()
- config.wg.Done()
- }
- func process(config *Config) {
- for i := 0; i < config.count; i++ {
- x1, x2 := <-config.input1, <-config.input2
- go calc(config, x1, x2, i)
- }
- config.wg.Wait()
- for i := 0; i < config.count; i++ {
- config.output <- config.repository[i]
- }
- close(config.output)
- }
- func Merge2Channels(f func(int) int, in1 chan int, in2 chan int, out chan int, n int) {
- task := Config{
- function: f,
- input1: in1,
- input2: in2,
- output: out,
- count: n,
- repository: make([]int, n),
- wg: new(sync.WaitGroup),
- repMutex: new(sync.Mutex)}
- go process(&task)
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement