Skip to content

Commit

Permalink
Add concurrency_test.go, mutex for Parallel
Browse files Browse the repository at this point in the history
We need the mutex because we call the go routine from our for loop and when
the first starts, the for-loop has already finished and i == n - 1. We now
lock our mutex, start the function (so no two functions have the same index)
and increment the counter.
  • Loading branch information
bahlo committed Aug 27, 2015
1 parent 7a8ce37 commit f0dd0b1
Show file tree
Hide file tree
Showing 2 changed files with 83 additions and 1 deletion.
14 changes: 13 additions & 1 deletion concurrency.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,9 +13,21 @@ func Parallel(n int, fn func(int)) {
wg.Add(n)
defer wg.Wait()

var m sync.Mutex
counter := 0

for i := 0; i < n; i++ {
go func() {
fn(n)
// Lock mutex to prevent multiple functions with the same index
m.Lock()

// Run function
fn(counter)

// Increment counter
counter++

m.Unlock()
wg.Done()
}()
}
Expand Down
70 changes: 70 additions & 0 deletions concurrency_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
package abutil

import (
"sync"
"testing"
"time"
)

func TestParallel(t *testing.T) {
var m sync.Mutex
var wg sync.WaitGroup

counter := 0

wg.Add(2)
go Parallel(2, func(n int) {
m.Lock()
counter++
m.Unlock()
wg.Done()
})

wg.Wait()

if counter != 2 {
t.Errorf("Expected counter to be %d, but got %d", 2, counter)
}
}

func TestParallelCounter(t *testing.T) {
var m sync.Mutex
var wg sync.WaitGroup

sum := 0
wg.Add(4)
go Parallel(4, func(n int) {
m.Lock()
sum += n
m.Unlock()
wg.Done()
})

wg.Wait()

if sum != 6 {
t.Errorf("Expected sum to be %d, but got %d", 6, sum)
}
}

func TestParallelTiming(t *testing.T) {
var m sync.Mutex
counter := 0

go Parallel(4, func(n int) {
time.Sleep(time.Duration(n) * time.Millisecond)
m.Lock()
counter++
m.Unlock()
})

done := make(chan bool)
time.AfterFunc(2*time.Millisecond, func() {
if counter != 2 {
t.Errorf("Expected counter to be %d, but got %d", 2, counter)
}
done <- true
})

<-done
}

0 comments on commit f0dd0b1

Please sign in to comment.