Kill Boost thread with another timeout thread

风格不统一 提交于 2020-01-16 02:02:24

问题


I want to end a thread WorkerThread after a certain amount of time has elapsed. I was thinking to use a second thread TimeoutThread for this, that changes a flag after 15 seconds so the other thread stops. Is there a more elegant way in boost to do this?

#include <boost/thread.hpp>

struct MyClass
{
    boost::thread timeoutThread;
    boost::thread workerThread;
    bool btimeout = true;

    void run()
    {
     timeoutThread = boost::thread(boost::bind(&MyClass::TimeoutThread, this));
      workerThread  = boost::thread(boost::bind(&MyClass::WorkerThread, this));
     workerThread.join();
     TimeoutThread.join();
    }


    void WorkerThread() {

        while(boost::this_thread::interruption_requested() == false && btimeout) 
        {
            printf(".");

        }
    }

    void TimeoutThread() 
    {
        boost::this_thread::disable_interruption oDisableInterruption;
        DWORD nStartTime = GetTickCount();

        while(boost::this_thread::interruption_requested() == false) 
        {
            if(GetTickCount() - nStartTime > 15)
            {
                m_bTimeout = false;
                break;
            }
        }

    }
};

int main()
{
    MyClass x;
    x.run();
}

回答1:


You could use a sleep:

#include <boost/thread.hpp>

struct MyClass
{
    boost::thread timeoutThread;
    boost::thread workerThread;

    void TimeoutThread() {
        boost::this_thread::sleep_for(boost::chrono::milliseconds(15));
        workerThread.interrupt();
    }

    void WorkerThread() {
        while(!boost::this_thread::interruption_requested())
        {
            //Do stuff
        }
    }

    void run()
    {
        timeoutThread = boost::thread(boost::bind(&MyClass::TimeoutThread, this));
        workerThread  = boost::thread(boost::bind(&MyClass::WorkerThread, this));
        workerThread.join();
        timeoutThread.join();
    }
};

int main()
{
    MyClass x;
    x.run();
}

This has the minimal benefit of being portable.

See it live on Coliru

Please be aware of the deadline_timer class in Boost Asio too.

And it looks like you're trying to await a condition in your worker thread. If so, you can also await a condition_variable with a deadline (cv.wait_until or with a timeout: cv.wait_for).




回答2:


Just check time in worker thread and you won't need a separate timeout thread:

void WorkerThread() 
{
    DWORD nStartTime = GetTickCount();
    while(boost::this_thread::interruption_requested() == false && GetTickCount() - nStartTime < 15000) 
    {
        printf(".");

    }
}

BTW, please note 15000, because GetTickCount() units are milliseconds



来源:https://stackoverflow.com/questions/22763146/kill-boost-thread-with-another-timeout-thread

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!