Skip to content
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

fix: race condition in close #37 #38

Merged
merged 1 commit into from
Jan 25, 2024

Conversation

bherw
Copy link

@bherw bherw commented Jan 24, 2024

Because the close method does not lock and the read method does not check the closed value after locking, it's possible for a deadlock to occur under the following series of events:

Thread 1 (reader): read last element from the channel
Thread 1: call operator>>
Thread 1: check closed(), which is false
Thread 1: lock mutex
Thread 1: check the predicate in wait()
Thread 2 (writer): call close()
Thread 2: set closed=true
Thread 2: call cnd_.notify_all()
Thread 1: calls wait() without predicate (in the implementation of the wait with predicate method)

At this point, Thread 1 waits forever because the notify_all occurred before the actual call to wait().

I don't have a good minimal test case for the issue here, but I have run it for several hours in a loop an integration test that was deadlocking before, so I'm fairly confident the issue is fixed.

Because the close method does not lock and the read method does not
check the closed value after locking, it's possible for a deadlock to
occur under the following series of events:

Thread 1 (reader): read last element from the channel
Thread 1: call operator>>
Thread 1: check closed(), which is false
Thread 1: lock mutex
Thread 1: check the predicate in wait()
Thread 2 (writer): call close()
Thread 2: set closed=true
Thread 2: call cnd_.notify_all()
Thread 1: calls wait() without predicate (in the implementation of the
wait with predicate method)

At this point, Thread 1 waits forever because the notify_all occurred
before the actual call to wait().
@andreiavrammsd
Copy link
Owner

It's great when someone uses the library in the real world.

Thank you!

@andreiavrammsd andreiavrammsd merged commit 51c39d5 into andreiavrammsd:master Jan 25, 2024
4 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.

None yet

2 participants