From 628c884543268ada62314bc0f9c092b430447675 Mon Sep 17 00:00:00 2001
From: Tiburon <ya@tiburon.su>
Date: Sun, 19 Jul 2020 11:25:01 +0300
Subject: [PATCH] =?UTF-8?q?=D0=A2=D1=80=D0=B0=D0=BD=D1=81=D1=84=D0=B5?=
 =?UTF-8?q?=D1=80=20=D0=BD=D0=B0=20=D0=B4=D1=80=D1=86=D0=B3=D0=BE=D0=B9=20?=
 =?UTF-8?q?=D0=BA=D0=BE=D0=BC=D0=BF?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit

---
 hw05_parallel_execution/go.mod |  2 +-
 hw05_parallel_execution/run.go | 22 +++++++++++++++++++++-
 2 files changed, 22 insertions(+), 2 deletions(-)

diff --git a/hw05_parallel_execution/go.mod b/hw05_parallel_execution/go.mod
index 89e9922..56368ea 100644
--- a/hw05_parallel_execution/go.mod
+++ b/hw05_parallel_execution/go.mod
@@ -1,4 +1,4 @@
-module github.com/fixme_my_friend/hw05_parallel_execution
+module github.com/tiburon-777/HW_OTUS/hw05_parallel_execution
 
 go 1.14
 
diff --git a/hw05_parallel_execution/run.go b/hw05_parallel_execution/run.go
index 6be37a4..54bfeef 100644
--- a/hw05_parallel_execution/run.go
+++ b/hw05_parallel_execution/run.go
@@ -2,6 +2,8 @@ package hw05_parallel_execution //nolint:golint,stylecheck
 
 import (
 	"errors"
+	"log"
+	"sync"
 )
 
 var ErrErrorsLimitExceeded = errors.New("errors limit exceeded")
@@ -10,6 +12,24 @@ type Task func() error
 
 // Run starts tasks in N goroutines and stops its work when receiving M errors from tasks
 func Run(tasks []Task, N int, M int) error {
-	// Place your code here
+	log.Println("Tasks:", len(tasks), "| Goroutines:", N, "| Errors:", M)
+	errs := 0
+	for i := 0; i < len(tasks); i = i + N {
+		wg := sync.WaitGroup{}
+		for g := 1; g <= N && i+g < len(tasks); g++ {
+			wg.Add(1)
+			go func(rt Task, i int, g int, errs *int) {
+				if err := rt; err != nil {
+					*errs++
+				}
+				wg.Done()
+			}(tasks[i+g], i, g, &errs)
+		}
+		wg.Wait()
+		if errs > M {
+			log.Println("Produced", errs, "errors of", M)
+			return ErrErrorsLimitExceeded
+		}
+	}
 	return nil
 }