开发者

How to make boost threads self-destruct? (C++)

开发者 https://www.devze.com 2023-01-24 03:57 出处:网络
I have a class with some function like: void workerFunc(int ClassVariable) { boost::posix_time::seconds workTime(classVariableA);

I have a class with some function like:

void workerFunc(int ClassVariable)  
{  
    boost::posix_time::seconds workTime(classVariableA);  

    std::cout << "Worker: running" << std::endl;  

    // Pretend to do something useful...  
    boost::this_thread::sleep(workTime);  


    std::cout << ClassVariable << std::end开发者_运维技巧l;  
    std::cout << "Worker: finished" << std::endl;  
}  

which I want to be in threads. and some other function that I want to work like

while(1)
{
 boost::thread workerThread(workerFunc(ClassVariableB));  
}

so it will create thread each time it can. But what I need is for that thread to auto destruct itself when it is finished. How to do such thing?


You do not have to do anything for that. You just have to make sure that the thread really finishes (i.e. no infinite loops or such).


A thread will automatically end when it finishes running the function for which it was created.

join is a strange word, it really means wait_for which means wait for the thread to finish executing.

If you want to retain a thread for re-use, it is normally implemented by making its function loop, each time reaching a "wait" state, where it gets alerted (woken up) when something it is waiting for happens. At some point this will be a termination request, or a request that leads to its termination.

0

精彩评论

暂无评论...
验证码 换一张
取 消