Thread Wait For Parent

后端 未结 5 425
一个人的身影
一个人的身影 2020-12-10 19:30

I am implementing a simple thread pool mechanism for my ubuntu server (for my multi-client anonymous chat program), and I need to make my worker threads sleep until a job (i

5条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-10 19:31

    The usual way this is implemented is to have a queue queue of outstanding work, a mutex mutex protecting the queue, and a wait condition queue_not_empty. Then, each worker thread does the following (using pseudo-api):

    while (true) {
        Work * work = 0;
        mutex.lock();
        while ( queue.empty() )
           if ( !queue_not_empty.wait( &mutex, timeout ) )
               return; // timeout - exit the worker thread
        work = queue.front();
        queue.pop_front();
        mutex.unlock();
        work->perform();
    }
    

    The wait( &mutex, timeout ) call blocks until either the wait condition is signaled, or the call times out. The mutex passed is atomically unlocked inside wait(), and locked again before returning from the call, to provide a consistent view of the queue to all participants. timeout would be chosen rather large (seconds), and would lead to the thread exiting (the thread pool would start new ones if more work came in).

    Meanwhile, the thread pool's work insertion function does this:

    Work * work = ...;
    mutex.lock();
    queue.push_back( work );
    if ( worker.empty() )
        start_a_new_worker();
    queue_not_empty.wake_one();
    mutex.unlock();
    

提交回复
热议问题