Is this method of protecting shared data reasonable?

I'm re-factoring a program I started when I was much less experienced. I used a simple method to "lock" some data which is shared between two threads; something along these lines.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
volatile bool lock;
bool isLocked();
void lock();
void unlock();

//thread1
while(islocked()) usleep(1);
lock();
writeArr(arr);
unlock();

//thread2
while(islocked()) usleep(1);
lock();
readArr(arr);
unlock();


Without the "lock" there are problems. But with it I can't seam to cause any undesired behavior.

What's wrong with this method? What can go wrong?
Last edited on
Both threads call lock at the same time and simultaneously write and read the data?
Last edited on
I just realized I should just use std::atomic <bool>.

1
2
3
4
5
std::atomic <bool> lock;

while (lock.exchange(true)) {}
//do stuff
lock = false;


http://www.drdobbs.com/parallel/measuring-parallel-performance-optimizin/212201163?pgno=3


Last edited on
Topic archived. No new replies allowed.