The goal of a mutex is to make sure only one work-item can access critical data at a time. I've tried to implement a mutex with the atomic_cmpxchg function, which atomically performs the ternary operation (*x == y) ? z : *x
To test the mutex, I tried the following code:
Code :__local mutex; mutex = 0; while(atomic_cmpxchg(&mutex, 0, 1) == 1); ... atomic_xchg(&mutex, 0);
The while statement checks the value of mutex. If the value is 1 (the locked state), it keeps waiting. But if the value is 0 (the unlocked state), the work-item should set the value to 1 and proceed to the following code. Then the last line sets the mutex to 0 (the unlocked state).
But when I run this code, my graphics card hangs. Has anyone else tried to implement a mutex in OpenCL?