Skip to content
Advertisement

Futex and pthreads issue

I’m testing futexes with pthreads. I’ve written following program:

JavaScript

And sometimes it returns 0 as a sum which is proper value but sometimes the returned value of sum is different than 0.

My question is why the returned values of “sum” are different than 0? I suspect that there is something wrong with locking but for the moment I cannot figure out what.

Advertisement

Answer

The problem with your implementation is the way you use the atomic_compare_exchange_strong(). Note that, from C reference that:

[If compare fails], loads the actual contents of memory pointed to by obj into *expected (performs load operation).

In your code, that means that when this atomic operation fails (i.e. futx is not 1) the value of futx will be loaded at one, meaning that now one value is now 0.

From now, the lock function is broken giving that the atomic operation will succeed (i.e. futx has the same value as one, that is 0) even when the lock is taken, meaning that we can have more than one thread holding it at the same time. To fix this you need to either resets one every loop:

JavaScript

Or even better, always set the lock as taken and check if the previous value was the value for free lock:

JavaScript

If you use defines for your futexes values it makes the understanding easier. In your case:

JavaScript
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement