Created
May 3, 2023 02:44
-
-
Save fujimaki-k/5a57d79bbc6d56c60115fc42d7bf7471 to your computer and use it in GitHub Desktop.
Alternative concurrent example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"errors" | |
"fmt" | |
"runtime" | |
"sync" | |
) | |
// Concurrent is concurrently execute tasks for number of CPUs. | |
func Concurrent(items chan any, task func(any)) { | |
WithN(runtime.NumCPU(), items, task) | |
} | |
// WithN is concurrently execute tasks for number of threads. | |
func WithN(threads int, items chan any, task func(any)) { | |
if len(items) < 1 { | |
return | |
} | |
if len(items) < threads || threads < 0 { | |
threads = len(items) | |
} | |
var wg sync.WaitGroup | |
filled := make([]chan bool, threads) | |
wg.Add(len(items)) | |
for i := 0; i < threads; i++ { | |
filled[i] = execute(&wg, items, task) | |
} | |
wg.Wait() | |
for _, done := range filled { | |
done <- true | |
close(done) | |
} | |
} | |
// Execute is execute task in goroutine. | |
func execute(wg *sync.WaitGroup, items chan any, task func(any)) chan bool { | |
done := make(chan bool, 1) | |
go func() { | |
for { | |
select { | |
case value := <-items: | |
task(value) | |
wg.Done() | |
case <-done: | |
return | |
} | |
} | |
}() | |
return done | |
} | |
func main() { | |
values := []string{"Honoka", "Kotori", "Umi", "Maki", "Rin", "Hanayo", "Nico", "Nozomi", "Eli"} | |
items := make(chan any, len(values)) | |
defer close(items) | |
for _, value := range values { | |
items <- value | |
} | |
rejects := make(chan error, len(values)) | |
defer close(rejects) | |
Concurrent(items, func(value any) { | |
if value == "Honoka" || value == "Kotori" || value == "Hanayo" { | |
rejects <- errors.New("fight dayo!") | |
return | |
} | |
fmt.Println(value) | |
}) | |
for { | |
select { | |
case err := <-rejects: | |
fmt.Println(err) | |
default: | |
return | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment