30 Aug
2007
30 Aug
'07
7:35 p.m.
Well... let's take the example of an interruptible task. We have a main program which launches a thread. Now, we want to stop this thread. We can use interruption or the following code:
T1: while(true) { lock lk(mutex); if (end) break;
lk.unlock();
/* dosomething */ }
T2: interruptT1() { lock lk(mutex); end = true; }
T2 only needs access to 'end', it doesn't touch the shared state modified by 'dosomething', so it doesn't need to be prevented from running in parallel with 'dosomething'. The general rule is to keep the critical regions as short as possible and not reuse the same mutex for unrelated tasks. In this specific case one can also use an atomic variable, of course.