Delayed start of a thread in C++ 11

前端 未结 6 1958
南方客
南方客 2020-12-01 09:05

I\'m getting into C++11 threads and have run into a problem.

I want to declare a thread variable as global and start it later.

However all the examples I\'ve

6条回答
  •  执念已碎
    2020-12-01 09:25

    I would give the thread a condition variable and a boolean called startRunning (initially set to false). Effectively you would start the thread immediately upon creation, but the first thing it would do is suspend itself (using the condition_variable) and then only begin processing its actual task when the condition_variable is signaled from outside (and the startRunning flag set to true).

    EDIT: PSEUDO CODE:

    // in your worker thread
    {
        lock_guard l( theMutex );
    
        while ( ! startRunning )
        {
            cond_var.wait( l );
        }
    }
    
    // now start processing task
    
    
    // in your main thread (after creating the worker thread)
    {
        lock_guard l( theMutex );
        startRunning = true;
        cond_var.signal_one();
    }
    

    EDIT #2: In the above code, the variables theMutex, startRunning and cond_var must be accessible by both threads. Whether you achieve that by making them globals or by encapsulating them in a struct / class instance is up to you.

提交回复
热议问题