Advertisement
Guest User

Task-E

a guest
May 28th, 2020
140
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Go 1.07 KB | None | 0 0
  1. package main
  2.  
  3. import (
  4.     "math/rand"
  5.     "sync"
  6.     "time"
  7. )
  8.  
  9. type Config struct {
  10.     repMutex   *sync.Mutex
  11.     function   func(int) int
  12.     input1     <-chan int
  13.     input2     <-chan int
  14.     output     chan int
  15.     count      int
  16.     repository []int
  17.     wg         *sync.WaitGroup
  18. }
  19.  
  20. func calc(config *Config, x1 int, x2 int, i int) {
  21.     config.wg.Add(1)
  22.     config.repMutex.Lock()
  23.     config.repository[i] = config.function(x1) + config.function(x2)
  24.     config.repMutex.Unlock()
  25.     config.wg.Done()
  26. }
  27.  
  28. func process(config *Config) {
  29.     for i := 0; i < config.count; i++ {
  30.         x1, x2 := <-config.input1, <-config.input2
  31.         go calc(config, x1, x2, i)
  32.     }
  33.     config.wg.Wait()
  34.  
  35.     for i := 0; i < config.count; i++ {
  36.         config.output <- config.repository[i]
  37.     }
  38.     close(config.output)
  39. }
  40.  
  41. func Merge2Channels(f func(int) int, in1 chan int, in2 chan int, out chan int, n int) {
  42.     task := Config{
  43.         function:   f,
  44.         input1:     in1,
  45.         input2:     in2,
  46.         output:     out,
  47.         count:      n,
  48.         repository: make([]int, n),
  49.         wg:         new(sync.WaitGroup),
  50.         repMutex:   new(sync.Mutex)}
  51.  
  52.     go process(&task)
  53. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement