Решение на Concurrent Retry Executor от Слави Боянов

Обратно към всички решения

Към профила на Слави Боянов

Резултати

  • 10 точки от тестове
  • 0 бонус точки
  • 10 точки общо
  • 9 успешни тест(а)
  • 0 неуспешни тест(а)

Код

package main
func scheduler(tasks []func() string, limit int, retries int, output chan<- struct {
index int
result string
}) {
semaphore := make(chan struct{}, limit)
for index, task := range tasks {
semaphore <- struct{}{}
go func(index int, task func() string) {
defer func() {
<-semaphore
}()
for i := 0; i < retries; i++ {
result := task()
output <- struct {
index int
result string
}{index, result}
if result != "" {
return
}
}
}(index, task)
}
go func() {
for i := 0; i < limit; i++ {
semaphore <- struct{}{}
}
close(output)
}()
}
func ConcurrentRetryExecutor(tasks []func() string, limit int, retries int) <-chan struct {
index int
result string
} {
output := make(chan struct {
index int
result string
})
go scheduler(tasks, limit, retries, output)
return output
}

Лог от изпълнението

PASS
ok  	_/tmp/d20161115-21147-vkd31a	0.003s
PASS
ok  	_/tmp/d20161115-21147-vkd31a	0.026s
PASS
ok  	_/tmp/d20161115-21147-vkd31a	0.026s
PASS
ok  	_/tmp/d20161115-21147-vkd31a	0.003s
PASS
ok  	_/tmp/d20161115-21147-vkd31a	0.003s
PASS
ok  	_/tmp/d20161115-21147-vkd31a	0.074s
PASS
ok  	_/tmp/d20161115-21147-vkd31a	0.218s
PASS
ok  	_/tmp/d20161115-21147-vkd31a	0.441s
PASS
ok  	_/tmp/d20161115-21147-vkd31a	0.203s

История (1 версия и 2 коментара)

Слави обнови решението на 15.11.2016 12:05 (преди над 1 година)

+package main
+
+func scheduler(tasks []func() string, limit int, retries int, output chan<- struct {
+ index int
+ result string
+}) {
+ semaphore := make(chan struct{}, limit)
+ for index, task := range tasks {
+ semaphore <- struct{}{}
+ go func(index int, task func() string) {
+ defer func() {
+ <-semaphore
+ }()
+ for i := 0; i < retries; i++ {
+ result := task()
+ output <- struct {
+ index int
+ result string
+ }{index, result}
+ if result != "" {
+ return
+ }
+ }
+ }(index, task)
+ }
+
+ go func() {
+ for i := 0; i < limit; i++ {
+ semaphore <- struct{}{}
+ }
+ close(output)
+ }()
+}
+
+func ConcurrentRetryExecutor(tasks []func() string, limit int, retries int) <-chan struct {
+ index int
+ result string
+} {
+ output := make(chan struct {
+ index int
+ result string
+ })
+ go scheduler(tasks, limit, retries, output)
+ return output
+}