Skip to content

Commit

Permalink
Merge pull request #13 from fsouza/remove-mutex
Browse files Browse the repository at this point in the history
parallel: remove mutex from Map and Times
  • Loading branch information
samber committed Mar 5, 2022
2 parents 094b6f9 + 770dff2 commit ab4e214
Show file tree
Hide file tree
Showing 2 changed files with 8 additions and 11 deletions.
3 changes: 3 additions & 0 deletions map_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,9 @@ func TestEntries(t *testing.T) {

r1 := Entries[string, int](map[string]int{"foo": 1, "bar": 2})

sort.Slice(r1, func(i, j int) bool {
return r1[i].Value < r1[j].Value
})
is.EqualValues(r1, []Entry[string, int]{
{
Key: "foo",
Expand Down
16 changes: 5 additions & 11 deletions parallel/slice.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,17 +7,14 @@ import "sync"
func Map[T any, R any](collection []T, iteratee func(T, int) R) []R {
result := make([]R, len(collection))

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

for i, item := range collection {
go func (_item T, _i int) {
go func(_item T, _i int) {
res := iteratee(_item, _i)

mu.Lock()
result[_i] = res
mu.Unlock()

wg.Done()
}(item, i)
Expand All @@ -35,7 +32,7 @@ func ForEach[T any](collection []T, iteratee func(T, int)) {
wg.Add(len(collection))

for i, item := range collection {
go func (_item T, _i int) {
go func(_item T, _i int) {
iteratee(_item, _i)
wg.Done()
}(item, i)
Expand All @@ -50,17 +47,14 @@ func ForEach[T any](collection []T, iteratee func(T, int)) {
func Times[T any](count int, iteratee func(int) T) []T {
result := make([]T, count)

var mu sync.Mutex
var wg sync.WaitGroup
wg.Add(count)

for i := 0; i < count; i++ {
go func(_i int) {
item := iteratee(_i)

mu.Lock()
result[_i] = item
mu.Unlock()

wg.Done()
}(i)
Expand All @@ -81,7 +75,7 @@ func GroupBy[T any, U comparable](collection []T, iteratee func(T) U) map[U][]T
wg.Add(len(collection))

for _, item := range collection {
go func (_item T) {
go func(_item T) {
key := iteratee(_item)

mu.Lock()
Expand All @@ -91,7 +85,7 @@ func GroupBy[T any, U comparable](collection []T, iteratee func(T) U) map[U][]T
}

result[key] = append(result[key], _item)

mu.Unlock()
wg.Done()
}(item)
Expand All @@ -106,7 +100,7 @@ func GroupBy[T any, U comparable](collection []T, iteratee func(T) U) map[U][]T
// determined by the order they occur in collection. The grouping is generated from the results
// of running each element of collection through iteratee.
// `iteratee` is call in parallel.
func PartitionBy[T any, K comparable](collection []T, iteratee func (x T) K) [][]T {
func PartitionBy[T any, K comparable](collection []T, iteratee func(x T) K) [][]T {
result := [][]T{}
seen := map[K]int{}

Expand Down

0 comments on commit ab4e214

Please sign in to comment.