Skip to content

fix(pool): avoid race conditions when a task is submitted while the pool is stopping #105

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Apr 3, 2025

Conversation

alitto
Copy link
Owner

@alitto alitto commented Mar 29, 2025

This pull request provides an alternative solution to the one proposed by @korotin in his pull request #104 to address a race condition that can occur on workersWaitGroup when tasks are submitted while the pool is stopping.

Changes

  • Ensure closed atomic bool is toggled and checked while holding the mutex to avoid race conditions.
  • Ensure workersWaitGroup.Add() is always called while holding the mutex to avoid race conditions.
  • Improve comments on submit methods to clarify the behavior when the pool is stopped.
  • Refactor trySubmit method to make it simpler and more clear.
  • Centralize worker launch in a new method called launchWorker.
  • Replace subpoolSubmit with subpoolWorker method.

Fixes

  • Decrement workerCount counter when the pool context is cancelled.
  • Resize() now supports setting maxConcurrency to 0 (no limit)

Copy link

codecov bot commented Mar 29, 2025

Codecov Report

Attention: Patch coverage is 91.04478% with 6 lines in your changes missing coverage. Please review.

Project coverage is 95.27%. Comparing base (1ad365a) to head (0ccf029).
Report is 2 commits behind head on main.

Files with missing lines Patch % Lines
pool.go 91.04% 5 Missing and 1 partial ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main     #105      +/-   ##
==========================================
+ Coverage   94.62%   95.27%   +0.65%     
==========================================
  Files          11       11              
  Lines         725      720       -5     
==========================================
  Hits          686      686              
+ Misses         35       31       -4     
+ Partials        4        3       -1     

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@korotin
Copy link
Collaborator

korotin commented Mar 29, 2025

Hey @alitto !

I prefer your solution over mine for its simplicity. It reduces the chance of a data race significantly, but doesn't eliminate it completely because WaitGroup.Add and WaitGroup.Wait still stay unsynchronized.

Please take a look at a slightly modified test from my PR that proves data race is still there (better to run this one standalone — go test -race -v -timeout 15s -count=1 -test.run '^TestSubmitClose$'):

func TestSubmitClose(t *testing.T) {
	pool := NewPool(0)

	wg := sync.WaitGroup{}

	wg.Add(1)
	go func() {
		defer wg.Done()

		time.Sleep(500 * time.Microsecond)
		pool.StopAndWait()
	}()

	for i := 0; i < 100000; i++ {
		wg.Add(1)
		go func() {
			defer wg.Done()

			pool.Submit(func() {
				time.Sleep(10 * time.Millisecond)
			})
		}()
	}

	wg.Wait()
}

@liznear
Copy link

liznear commented Mar 30, 2025

IIUC, the unlock operation needs to be done at the end of trySubmit?

@korotin
Copy link
Collaborator

korotin commented Mar 30, 2025

@liznear that seems legit to me.

@alitto alitto force-pushed the fix/AD/submit-while-stopping branch from f39b7c7 to 72cb0d4 Compare April 2, 2025 12:13
@alitto alitto force-pushed the fix/AD/submit-while-stopping branch from 72cb0d4 to 9e8faee Compare April 2, 2025 12:14
@alitto
Copy link
Owner Author

alitto commented Apr 2, 2025

Thanks @korotin for providing that test 🙌, i added it to pool_test.go to ensure there's no data race around workersWaitGroup.
@liznear unlocking at the end of trySubmit would do the trick but after some rearrangements of the code in that method I was able to make sure all calls to p.workersWaitGroup.Add(1) are made while holding the lock, so it should be equivalent to what you are proposing. The key difference is the lock is not held while launching the goroutine, but that's not really necessary to avoid a data race here so better to keep it outside.
I ended up refactoring the trySubmit method to reduce the number of branches and move all if statements to the top. Also, now all calls to increment/decrement workerCount and workersWaitGroup are grouped together and always performed while holding the lock. It looks cleaner and it should prevent data races. While doing this I noticed workerCount was not being decremented when the context was cancelled, so this PR fixes that too.
I left calls to workersWaitGroup.Wait() not synchronized because it's not necessary given the swapping of the closed flag is synchronized. This ensures there won't be any calls to workersWaitGroup.Add(1) once closed is set to true, because this flag is checked before deciding to launch a new worker in a synchronized manner.
Thoughts?

@alitto alitto force-pushed the fix/AD/submit-while-stopping branch from 4430a43 to 0ccf029 Compare April 2, 2025 20:40
@korotin
Copy link
Collaborator

korotin commented Apr 3, 2025

@alitto seems like a nice and clean solution! 😎

@alitto alitto merged commit 3b89b22 into main Apr 3, 2025
15 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants