Defined Concurrency

Created Diff never expires
4 हटाए गए
लाइनें
कुल
हटाया गया
शब्द
कुल
हटाया गया
इस सुविधा का उपयोग जारी रखने के लिए, अपग्रेड करें
Diffchecker logo
Diffchecker Pro
24 लाइनें
21 जोड़े गए
लाइनें
कुल
जोड़ा गया
शब्द
कुल
जोड़ा गया
इस सुविधा का उपयोग जारी रखने के लिए, अपग्रेड करें
Diffchecker logo
Diffchecker Pro
41 लाइनें
import "sync"
import (
"runtime"
"sync"
)

var _concurrency = runtime.NumCPU()

func MaxConcurrency(concurrency int) {
_concurrency = concurrency
}


// Map manipulates a slice and transforms it to a slice of another type.
// Map manipulates a slice and transforms it to a slice of another type.
// `iteratee` is call in parallel. Result keep the same order.
// `iteratee` is call in parallel. Result keep the same order.
func Map[T any, R any](collection []T, iteratee func(T, int) R) []R {
func Map[T any, R any](collection []T, iteratee func(T, int) R) []R {
result := make([]R, len(collection))
result := make([]R, len(collection))


c := _concurrency
if c <= 0 {
c = len(collection)
}
routines := make(chan struct{}, c)

var wg sync.WaitGroup
var wg sync.WaitGroup
wg.Add(len(collection))


for i, item := range collection {
for i, item := range collection {
wg.Add(1)
go func(_item T, _i int) {
go func(_item T, _i int) {
defer wg.Done()

routines <- struct{}{}
res := iteratee(_item, _i)
res := iteratee(_item, _i)
<-routines


result[_i] = res
result[_i] = res

wg.Done()
}(item, i)
}(item, i)
}
}


wg.Wait()
wg.Wait()


return result
return result
}
}