On Thu, Aug 30, 2007 at 12:08:51PM -0400, frederic.mayot@sgcib.com wrote: Hi, I'm having a problem with mutexes.
In one thread T1 I have: while(!end) { /* TTT */ lock lk(mutex); dosomethingquick(); }
...
Oh yes, I know that. The thing is I don't know what to do. The code I gave is, in my opinion, something really common. I'm just wondering how other people do in such a case...
The code is totally and irrecoverably broken (from a threading perspective). There is no way to fix it if it has to retain its current form. The basic idea when using threads is to create parallelism. Thread T1 is inherently non-parallel. It simply cannot operate in parallel with anyone else who also needs to access the shared state that is protected by the mutex. As a simplified example, consider two threads of the above form. Given a "fair" mutex, they will be effectively equivalent to (and slightly slower than) a single thread that does: while( !end ) { dosomething_t1(); dosomething_t2(); } This may sound a bit unproductive, but it's hard to offer a general advice without knowing the specifics. As given, thread T1's effort is obviously wasted (it spins its wheels in place) so it has to be made to only wake up when it really has work to do.