How can I implement timer interrupt using pthreads?
+2
A:
I haven't ever seen any such facility in pthread itself, but you could always just use a SIGALARM handler which would notify a 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 of doing it would to simply using sleep/usleep in the thread itself.
Gianni
2010-07-20 12:41:40
A:
How about creating a thread, and in the thread function calling usleep() in a loop with your desired timer interval as the sleep value, each time also calling your timer "interrupt" callback function?
Frederik Slijkerman
2010-07-20 12:57:30