Pthread超时 [英] Pthread timeout

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

问题描述

我唯一想做的就是启动一个线程,看看它是否在一定时间内完成了.

All I waint to do is launch a thread and see if it has finished in a certain period of time.

OS:linux;语言:C ++.

OS: linux; language: C++.

我不想使用不可移植的功能(例如此答案中的建议).

I'd like not to use non portable functions (like suggested in this answer).

除了使用互斥锁和条件变量(如此处所示)?两个线程之间没有共享数据,因此从技术上讲,我不需要互斥体.对于启动线程的函数,我想要的只是继续执行

Is there any way to do that, other than using a mutex and a condition variable (as suggested here)? There is no shared data between the two threads, so technically I would not need a mutex. All I want is, for the function that launches the thread, to continue if

  • 线程已结束或

  • thread has finished or

已经过去了一段时间.

...并使代码尽可能简单.

... and keep the code as simple as I can.

推荐答案

如果要使用boost :: thread,则通常"的bool标志,条件变量,互斥量方法非常简单:

If you want to use boost::thread, the "usual" bool flag, condition variable, mutex approach is as simple as:

bool ready = false;
boost::mutex              mutex;
boost::condition_variable cv;

// function to be executed by your thread
void foo() 
{
    // lengthy calculation
    boost::mutex::scoped_lock lock( mutex );
    ready = true;
    cv.notify_one();
}

// will return, if the thread stopped
bool wait_for_foo( time_point abs_time )
{
    boost::mutex::scoped_lock lock( mutex );

    while ( !ready && cv.wait_until( lock, abs_time ) != cv_status::no_timeout )
      ;

    return ready;
}

好的,没有比使用posix;-)

Ok, isn't much simpler then using posix ;-)

这篇关于Pthread超时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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