Talk:Busy loop

From OSDev Wiki
Jump to: navigation, search

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

Personal tools
Namespaces
Variants
Actions
Navigation
About
Toolbox