Nov 27, 2012 at 6:56am UTC
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 Nov 27, 2012 at 7:10am UTC
Nov 27, 2012 at 7:09am UTC
Both threads call lock at the same time and simultaneously write and read the data?
Last edited on Nov 27, 2012 at 7:10am UTC
Nov 27, 2012 at 7:18am UTC
Last edited on Nov 28, 2012 at 6:23am UTC