Wake up all threads sleeping on futex

ghz 8months ago ⋅ 114 views

I want to wake up all threads sleeping on a futex. I am confused by an inconsistency in the man futex page.

Specifically, the page says that val has type uint32_t. Later on, in the FUTEX_WAKE section, the page says that to wake up all threads, pass INT_MAX to val.

INT_MAX is for signed integers, not unsigned integers. I would expect to pass UINT32_MAX instead. Though I could also anticipate the argument that the val variable is reused for different things and so INT_MAX is still the correct option since val is cast to an int in the kernel.

What is the correct way to do this?

Answers

You're correct to note the inconsistency in the man page for futex. Let's clarify the usage of FUTEX_WAKE and the value to wake up all threads.

The FUTEX_WAKE operation wakes up a specified number of waiting threads, not all of them. To wake up all threads waiting on a futex, you would indeed need to pass a large value, but not necessarily INT_MAX. Instead, you should use the maximum possible value for the data type val, which is UINT32_MAX for a uint32_t type.

The confusion might arise because val is actually treated as a signed integer in the kernel, and the kernel performs a comparison with val as a signed integer. Therefore, passing INT_MAX may also work in practice, as it will be interpreted as the largest positive signed integer value.

However, for clarity and consistency with the data type of val, it's better to use UINT32_MAX when you want to wake up all threads waiting on a futex.

So, the correct way to wake up all threads waiting on a futex is to use UINT32_MAX as the value for val in the FUTEX_WAKE operation.