Please take a look at the following code snippet using OpenMP for parallelization:
char lock = 0;
#pragma omp parallel
{
while(!__sync_bool_compare_and_swap(&lock, 0, 1));
printf("Thread: %d is working!\n", omp_get_thread_num());
sleep(1);
printf("Thread: %d unlocks lock!\n", omp_get_thread_num());
lock = 0;
}
Is it possible, that threads simultaneously lock the lock, even though the locking is atomic with __sync_bool_compare_and_swap? For example, not all threads having a consistent view of the memory?