Timer interrupt for pthreads

How can I implement timer interrupt using pthreads?

+3
source share
3 answers

I have never seen such an object in pthread itself, but you can always just use the SIGALARM handler , which would notify the thread using a semaphore .

EDIT:

#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;
}

Another way to do this is to simply use sleep / usleep in the thread itself.

+3
source

How to create a thread and a thread function that calls usleep () in a loop with your desired timer interval as a sleep value, each time also calling the interrupt callback function?

+2

usleep will skew all the time. at the end of the year, you would have split up a bit, so Linux provides timers.

0
source

Source: https://habr.com/ru/post/1755505/


All Articles