Bogdan M.
Bogdan M.

Reputation: 2191

Alarm() can be used in multithreading like this?

I'm curious if I am able to do the following with the unistd c function alarm(int signal)

Having my main.... and for each thread hat is created to initializate a SIGALRM with the function, which should close my thread in case of activating. Is this possible? or 1 SIGALRM / main is legal only?

Upvotes: 0

Views: 3454

Answers (2)

LtWorf
LtWorf

Reputation: 7608

Each thread in a process has an independent signal mask, which indicates the set of signals that the thread is currently blocking. A thread can manipulate its signal mask using pthread_sigmask(3). In a traditional single-threaded application, sigprocmask(2) can be used to manipulate the signal mask.

from man 7 signal.

The problem is that alarm works per process, not per thread, so if the sigmask of the threads is the same, you can't really know which one will receive the signal.

Upvotes: 2

Mike
Mike

Reputation: 49523

OK, so first, the alarm() is actually taking an unsigned int value which is the number of seconds before it expires. So your example int signal isn't the correct implementation of alarm(), just FYI.

As far as this goes:

for each thread that is created to initialization a SIGALRM
The SIGALRM that is generated is done so for the process not per thread, so you will have to catch the alarm and have some internal strategy to know which thread you raised it for and handle that accordingly. Once you have your handler, you can raise the alarm over and over again, however keep in mind:

Alarm requests are not stacked;

So you'll have to do this one at a time. It's still possible, but not totally stright forward as you were hoping.

For very rough example of what I'm talking about:

  • you have a "manager" which keeps track of requests
  • thread 1 tells the manager it needs to handle something in 10s
  • the manager "records" this and calls set alarm(10)
  • thread 2 tells the manager it needs to be woken up in 3 seconds
  • the manager calls alarm(0) to kill the alarm, calls alarm(3) then notes that once that goes off it needs to call alarm(7) to finish thread 1's sleep time
  • in your alarm handler you just call the manager and let it know an alarm went off and it will wake the appropriate thread (2) then reset the alarm for the next one.

Upvotes: 2

Related Questions