Using lockless atomic operations instead of a mutex
I recently had an interview where I was asked to show how to prevent race conditions in C or C++ between two threads operating on shared data. I used a mutex as follows : pthread_mutex_t mutex; int shared_var = 0; void thread1() { pthread_mutex_lock(&mutex); // Lock the mutex if (shared_var == 3) { // do something, then decrement shared_var shared_var--; } pthread_mutex_unlock(&mutex); // Unlock the mutex } void thread2() { pthread_mutex_lock(&mutex); // Lock the mutex shared_var++; pthread_mutex_unlock(&mutex); // Unlock the mutex } Then I was asked to do this in a lockless way using atomic v
0 upvotes
View original discussion ↗
Comments
Sign in or sign up to comment and upvote.
No comments yet.