76
General Discussion about just::thread / Re: is it possible to tell a thread to wait without using a lock
« on: November 25, 2008, 08:12:48 AM »I am not sure if I understand the unique_lock very well. I have this scenerio with the MT algorithm.
I have determined that there is no gain to the algorithm if the generate method has to initialize the threads every time before twisting the array[ 624 ].
I am taking an approach were the contructor creates the threads at the time that the CRandomMT is instantiated. I assign a block of the array to each thread. then I want each thread to stay running for the lifetime of the CRandomMT random number generator. I also want the threads to wait until I queue them to twist there block of the array. then once they are done wait again until they are queued to do it again.
each block of the array is isolated from another block of the array.
does a unique_lock provide this functionality or does it behave differently?
Just to recap: you want the threads to wait for some condition (you want the threads to twist their block of the array), perform their operation and then resume waiting on the condition.
That sounds like a job for a condition variable:
Code: [Select]
std::condition_variable cond;
std::mutex m;
bool do_twist=false;
bool done_twist=false;
void twister_thread(char* array_block_start)
{
for(;;)
{
std::unique_lock<std::mutex> ul(m);
done_twist=false;
while(!do_twist)
cond.wait(ul);
ul.unlock(); // we don't need to hold the lock whilst we do the twist
do_twist(array_block_start);
ul.lock(); // lock the mutex again
done_twist=true;
}
}
The controlling thread can then lock the mutex, set do_twist to true and call cond.notify_one() to wake the twisting thread. If you have multiple twisting threads and you want them all to process together, use the same condition variable for all of them and call cond.notify_all() to wake all of them.