用另一个超时线程杀死Boost线程 [英] Kill Boost thread with another timeout thread

查看:120
本文介绍了用另一个超时线程杀死Boost线程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在经过一定时间后结束线程 WorkerThread .我当时正在考虑使用第二个线程 TimeoutThread ,它在15秒后更改了一个标志,因此另一个线程停止了.有没有更优雅的方式来促进这一目标?

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();
}

推荐答案

您可以使用睡眠:

#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.

查看 在Coliru上直播

See it live on Coliru

请也注意Boost Asio中的 deadline_timer 类.

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

看起来您正在尝试等待工作线程中的条件.如果是这样,您还可以等待带有期限的 condition_variable ( cv.wait_until 或超时: cv.wait_for ).

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).

这篇关于用另一个超时线程杀死Boost线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆