The only time I can think about where RAII was not a solution is multi-threaded blocking a critical region. In general, it is advisable to obtain a critical region lock (think about this resource) and hold it in the RAII object:
void push( Element e ) { lock l(queue_mutex);
But there are situations when you cannot use RAII for this purpose. In particular, if the variable used in the loop state is shared by several threads, and you cannot hold the lock for the whole loop, then you must acquire and release the lock using another mechanism:
void stop_thread() { lock l(control_mutex); exit = true; } void run() { control_mutex.acquire(); while ( !exit ) {
Perhaps even now you can use RAII with (ab) using operator, which I think of, but I never thought about that. But I think this is not so natural:
void run() { while ( lock(control_mutex), !exit ) {
So, I think the answer is that I cannot imagine ...
EDIT: Other solutions for the same problem using RAII:
@ Mark Ransom :
bool should_exit() const { lock l(mutex); return exit; } void run() { while ( !should_exit() ) {
@ fnieto :
void run() { while (true) { { lock l(mutex); if (exit) break; }
David Rodríguez - dribeas
source share