m-ou-se / rust-atomics-and-locks

Code examples, data structures, and links from my book, Rust Atomics and Locks.
Other
1.33k stars 120 forks source link

is it possible for the receiver thread hanging forever? #10

Closed Daniel-Xu closed 1 year ago

Daniel-Xu commented 1 year ago

The content that the question is about

2023-01-30 at 8 36 PM

In Chapter 5. Building Our Own Channels

the implementation is from Safety Through Runtime Checks

The question

is it possible for the receiver thread hanging forever?

my reasoning

For is_ready, the sender thread stores true with Release ordering and then unpark the Receiver thread. After woken up, the receiver thread will check the is_ready again. However, it's possible that the return value is still false because we are using simple load.

This will park the receiver thread again and no other events will wake it up, thus hanging forever.

m-ou-se commented 1 year ago

That is a great question!

The answer is, fortunately: no, this won't hang forever. However, the reason for that is subtle and not actually fully explained in the book. (I might go a bit deeper into that in a next edition of the book.)

The reason this won't hang forever, is that unpark() forms a happens-before relationship with the park() call that it wakes up. (See the comment in the implementation here.)

I'll see if we can document that better and make it a proper guarantee.

Daniel-Xu commented 1 year ago

image Thanks so much @m-ou-se , I got it now after reading the source code of park & unpark