Skip to content

Commit

Permalink
Fix race condition (#2)
Browse files Browse the repository at this point in the history
* Fix race condition with CancelAll

* Update CHANGELOG
  • Loading branch information
mec07 committed Jan 29, 2020
1 parent 29c3fa1 commit 1bed86b
Show file tree
Hide file tree
Showing 3 changed files with 20 additions and 9 deletions.
7 changes: 7 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,12 @@

All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).

## [0.2.2] - 2020-01-29

### Fixed

- Fix race condition in CancelAll

## [0.2.1] - 2020-01-28

### Changed
Expand Down Expand Up @@ -34,3 +40,4 @@ All notable changes to this project will be documented in this file. The format
### Added

- initial commit of rununtil library

12 changes: 3 additions & 9 deletions rununtil.go
Original file line number Diff line number Diff line change
Expand Up @@ -95,22 +95,17 @@ type canceller struct {

func (canc *canceller) addChannel(key string, c chan struct{}) {
canc.mux.Lock()
defer canc.mux.Unlock()
canc.signals[key] = c
canc.mux.Unlock()
}

func (canc *canceller) removeChannel(key string) {
canc.mux.Lock()
delete(canc.signals, key)
canc.mux.Unlock()
}

func (canc *canceller) cancelAll() {
canc.mux.Lock()
defer canc.mux.Unlock()
for key := range canc.signals {
close(canc.signals[key])
delete(canc.signals, key)
}
canc.mux.Unlock()
}

var globalCanceller canceller
Expand Down Expand Up @@ -146,7 +141,6 @@ func AwaitKillSignals(signals []os.Signal, runnerFuncs ...RunnerFunc) {
finish := make(chan struct{})
uuid := uuid.New()
globalCanceller.addChannel(uuid.String(), finish)
defer globalCanceller.removeChannel(uuid.String())

for _, runner := range runnerFuncs {
shutdown := runner()
Expand Down
10 changes: 10 additions & 0 deletions rununtil_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -147,9 +147,19 @@ func TestRununtilCancelAll_MultipleTimes(t *testing.T) {
}

func TestRununtilCancelAll_Threadsafe(t *testing.T) {
var hasBeenKilledVec [100]bool
for idx := 0; idx < 100; idx++ {
cancel := rununtil.Killed(helperMakeMain(&hasBeenKilledVec[idx]))
cancel()
rununtil.CancelAll()
}
// yield control back to scheduler so that killing can actually happen
time.Sleep(time.Millisecond)
for idx, hasBeenKilled := range hasBeenKilledVec {
if !hasBeenKilled {
t.Fatalf("expected main to have been killed: %d", idx)
}
}
}

// Annoyingly this test has to be run by itself to actually fail...
Expand Down

0 comments on commit 1bed86b

Please sign in to comment.