2

我想做的就是启动一个线程,看看它是否在一段时间内完成。

操作系统:Linux;语言:C++。

我不想使用不可移植的功能(就像这个答案中建议的那样)。

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

  • 线程已完成或

  • 一定的时间过去了。

...并尽可能保持代码简单。

4

3 回答 3

2

如果你想使用 boost::thread,“通常的”布尔标志、条件变量、互斥锁方法很简单:

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 简单得多;-)

于 2012-07-18T13:22:40.053 回答
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;
}
于 2014-02-21T20:32:20.290 回答
0

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

于 2012-07-18T13:00:23.057 回答