forked from bahlo/abutil
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Add concurrency_test.go, mutex for Parallel
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
Showing
2 changed files
with
83 additions
and
1 deletion.
There are no files selected for viewing
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
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
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 | ||
} |