Talk:Busy loop

Revision as of 06:00, 9 June 2024 by Xtex (talk | contribs) (Bot: Replace deprecated source tag with syntaxhighlight)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)

Doesn't the sample code introduce a race condition between the while loop and the update? If two processes are attempting to lock the same mutex, and a switch occurs just after the first has seen mutex->in_use become false, but before it has set it to 1, then the second could also see it as false, set it to 1, and continue followed by the first doing the same thing once it's active again.

int lock(mutex *mutex) {
    // Wait for the mutex to become free.
    while(mutex->in_use);
    // Added: what if a task switch happens here?
    mutex->in_use = 1;
    return 0;
}

Answer: indeed that is a problem, specially in multicore. Atomic operations MUST be used here. There are GCC bultins that can do that for you without using assembly, like for example, __sync_bool_compare_swap, if I remember clear the name. --Atie

Return to "Busy loop" page.