Comment

Comment by ww520

It's important to remember that futex is not a lock; it is a conditional sleeping operation. Its name unfortunately looks similar to mutex but it's not a lock.

A thread calls futex(&flag, FUTEX_WAIT) to sleep. The kernel wakes up the caller thread when the futex flag's value might have been changed, by another thread calling futex(&flag, FUTEX_WAKE). When futex() returns, you don't get a lock. It just means the value of the flag might have been changed.

Since it's not a lock, the value of the flag is not guaranteed to be certain value when futex() returns. The flag can be changed again by another thread between the futex's return and the next instruction of the caller thread. It's important to put the futex() call inside a loop calling compare_and_set() repeatedly to check the expected value of the flag.

parent ww520 4 years ago

Discussion

Live from the official Hacker News API

A modern reader for Hacker News · SvelteKit + Skeleton