pthreads的定时器中断

时间:2010-07-20 12:31:36

标签: c++ linux pthreads interrupt

如何使用pthreads实现定时器中断?

3 个答案:

答案 0 :(得分:3)

我从未在pthread中看到任何此类工具,但您总是可以使用SIGALARM处理程序,该处理程序将使用semaphore通知线程。

编辑:

#include <iostream>
#include <string.h>
#include <errno.h>

#include <unistd.h>
#include <signal.h>

#include <pthread.h>
#include <semaphore.h>

static sem_t __semAlaram;

static void* waitForAlaram(void*)
{
    while( true )
    {
        sem_wait( &__semAlaram );
        std::cout << "Got alaram" << std::endl;
    }
    return NULL;
}


typedef void (*sighandler_t)(int);
static sighandler_t __handler = NULL;
static int count = 0;

static void sighandler(int signal)
{
    if ( signal == SIGALRM )
    {
        count++;
        sem_post( &__semAlaram );
        alarm(3);
    }
    else if ( __handler )
        __handler( signal );
}

int main(int argc, char **argv)
{
    if ( sem_init( &__semAlaram, 0, 0 ) != 0 )
    {
        std::cerr << strerror( errno ) << std::endl;
        return -1;
    }

    pthread_t thread;
    if ( pthread_create( &thread, NULL, waitForAlaram, NULL ) != 0 )
    {
        std::cerr << strerror( errno ) << std::endl;
        return -1;
    }

    __handler = signal( SIGALRM, sighandler );
    alarm(3);

    while( count < 5 )
    {
        sleep(1);
    }
    return 0;
}

另一种方法是在线程本身中简单地使用sleep / usleep。

答案 1 :(得分:2)

如何创建一个线程,并在线程函数中调用usleep()在一个循环中,并将所需的定时器间隔作为休眠值,每次还调用定时器“中断”回调函数?

答案 2 :(得分:0)

usleep将使所​​有时间都倾斜。在年底你会有相当多的漂移,这就是为什么linux提供计时器。

相关问题