1

I am implementing a program that uses threads. I want Each created thread to be delayed for a time. Then a signal is sent to the thread, and the handler should print a message. My issue is in sending a signal to a thread. how could it be possible to send an alarm signal to each thread created? I can use pthread_kill(), but how could I specify the time as in alarm(6) or so on?

void *thread(void *parameter)
{
       //How to send a signal to a thread
}
void threadHandler(int sig)
{
    printf("hello from thread\n");
}
RatDon
  • 3,403
  • 8
  • 43
  • 85

1 Answers1

0

Well, one possibility would be to make an additional thread which sleeps for a given amount of time using e.g. usleep and then uses pthread_kill to send the signal you want to send to the correct thread. If you e.g. want to send three signals, after 1, 3 and 5 seconds have passed, you can use this code:

usleep(1*1000*1000);
pthread_kill(thread1, SIGALRM);
usleep(2*1000*1000);
pthread_kill(thread2, SIGALRM);
usleep(2*1000*1000);
pthread_kill(thread3, SIGALRM);

If you're on Linux, you can use timerfd_create() to create a timer file descriptor from which data can be read after the given amount of time has passed. So, if you have e.g. 10 threads, you can create 10 timerfds with the thread-specific timeout and then use an epoll_wait() loop (see epoll_create and epoll_wait manual pages) which listens for data to be read from the timerfds and sends the signal to the correct thread once there is data to be read.

I don't think there is any ready-made interface that sends a SIGALRM signal to a specific thread after a specific amount of time has passed, but if creating an extra thread is an option you can definitely emulate it using usleep() or timerfd_create() / epoll_wait().

juhist
  • 4,210
  • 16
  • 33