Pthread超时

时间:2012-07-18 12:46:17

标签: c++ linux pthreads

我所要做的就是启动一个帖子,看看它是否在一段时间内完成。

OS:linux;语言:C ++。

我不想使用非便携式功能(如this answer中建议的那样)。

有没有办法做到这一点,除了使用互斥锁和 条件变量(如建议here)?两个线程之间没有共享数据,所以从技术上讲我不需要互斥锁。 对于启动线程的函数,我想要的只是

  • 主题已完成或

  • 过了一段时间。

...并尽可能简化代码。

3 个答案:

答案 0 :(得分:2)

如果你想使用boost :: thread,那么“通常的”bool标志,条件变量,互斥方法就像这样简单:

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并不简单; - )

答案 1 :(得分:1)

你可以创建计时器线程,一旦达到计时器,就会发现timeout取消。没有必要让mutex.code像:

#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>

#define TIMEOUT 1*60 //in secend
int count = 0;
pthread_t t_main;   //Thread id for main thread
void * timer_thread()
{
    while (TIMEOUT > count)
    {
        sleep(1);  //sleep for a secand
        count++;
    }
    printf("killinn main thread\n");
    pthread_cancel(t_main); // cancel main thread

}
void * m_thread()
{
    pthread_t t_timer; //Thread id for timer thread
    if (-1 == pthread_create(&t_timer, NULL, timer_thread, NULL))
    {
        perror("pthread_create");
        return NULL;
    }
    //DO your work...
    while(1)
    {
        sleep(2);
    }
}

int main()
{
        if ( -1 == pthread_create(&t_main, NULL, m_thread, NULL))
    {
        perror("pthread_create");
        return -1;
    }
    if (-1 == pthread_join(t_main, NULL))
    {
        perror("pthread_join");
        return -1;
    }
    return 0;
}

答案 2 :(得分:0)

你甚至不需要一个条件变量,你可以让另一个线程在进入时锁定一个互斥锁并在它完成时解锁它,并让启动线程使用pthread_mutex_timedlock(在旧版本的POSIX中可选) ,POSIX 2008中要求尝试获取互斥锁,如果另一个线程尚未完成则超时。

相关问题