pthread的定时器中断

3

我该如何使用pthread实现定时器中断?


你是指硬件为中心的NMI定时器中断(我认为无法在线程级别上完成),还是只是在周期性间隔内启动活动? - Pontus Gagge
如果您的意思是这样,那么您不能中断一个线程来执行一些代码,然后告诉它切换回之前正在做的事情;这被称为上下文切换,由操作系统完成。 - Tomaka17
然而,您可以定期检查条件并在其为真时执行某些操作,但您不需要任何特殊工具来实现此功能。 - Tomaka17
1
真的不清楚需要什么。 - n-alexander
3个回答

3

我从来没有在pthread本身中看到过这样的功能,但你可以使用SIGALARM处理程序,通过信号量通知线程。

编辑:

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

2
如何创建一个线程,然后在线程函数中使用usleep()函数在循环中调用,以您想要的定时器间隔作为睡眠值,在每次调用时还调用您的定时器“中断”回调函数?

0

使用 usleep 会使整体时间偏移。到年底时,您的时间可能会漂移相当多,这就是为什么 Linux 提供计时器的原因。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接