RoundRobin RoundRobin - 4 months ago 8x
Linux Question

Is this code with tset function free from race conditions or deadlocks?

  1. What does
    function mean in Linux? Is this function thread safe?

  2. Look at the code, is there a possibility for a race condition or a deadlock to occur?

thread1() { thread2() {
while (1) { while (1) {
if (!tset(&lm)) { if (!tset(&ln)) {
if (!tset(&ln)) { if (!tset(&lm)) {
x ++; x ++;
y ++; y ++;
break; break;
} }
else lm = false; else ln = false;
} }
} }
lm = false; ln = false;
ln = false; lm = false;
} }

enter image description here


tset here is probably a short form for test_and_set. Each thread tries to acquire both locks. If it succeeds, it increments the variables and releases the locks. Otherwise it gives up.

Looks like this is enough to avoid a race condition, assuming that tset is atomic.

Both threads use tset and release the lock immediately if they fail two acquire them. Therefore this code also is deadlock free.

However this does not mean that there are no problems with this code.

It is possible that the threads will keep acquiring and releasing locks without making any progress. This is situation is called livelock in concurrency theory.

If you have atomic test_and_set you could implement a proper critical section as Antti Haapala suggests in the comments.