I have two threads, one of which works in a narrow loop, and the other, which sometimes needs to synchronize with the first:
// thread 1 while(1) { lock(work); // perform work unlock(work); } // thread 2 while(1) { // unrelated work that takes a while lock(work); // synchronizing step unlock(work); }
My intention is that thread 2 can, by locking, effectively suspend thread 1 and perform the necessary synchronization. Topic 1 may also suggest pausing by unlocking, and if thread 2 is not waiting for a lock, lock again and return to work.
The problem I ran into is that the mutexes are not fair, so thread 1 quickly blocks the mutex and head stream 2. I tried using pthread_yield and so far everything is working fine, but I'm not sure that it will work for all systems / number of cores. Is there a way to ensure that thread 1 will always give thread 2, even in multi-core systems?
What is the most efficient way to handle this synchronization process?
c ++ multithreading pthreads
scientiaesthete
source share