Question

I'm trying to start a thread as soon as an interrupt occurs. However, I have realized that I can't start a thread from within an interrupt handler (or any function that is directly or indirectly being called by the interrupt handler). So, what I have decided to do is have the handler assert a flag. Then, a separate thread continously monitors that flag and if it's asserted it will in turn create (and start) a thread. Here's a pseudocode:

int interrupt_flag = 0;

interrupt_handler(void)
{
  interrupt_flag = 1
}

monitoring_thread(void) //this thread is started at the start of the program
{
  while(1)
  {
    if(interrupt_flag)
    {
      interrupt_flag = 0;
      //start the thread here
      sleep(/*some amount of time*/);
    }
  }
}

I'm not really happy with having a dedicated while loop constantly monitoring a flag. The problem with this is that it significantly reduces the speed of the other threads in my program. For this reason, I'm calling the sleep function to increase the speed of the other threads in my program.

Question: Is there a way I can truly start a thread upon interrupt, without having a dedicated while loop? Is there a workaround for starting a thread from within an interrupt handler?

If it makes any difference, I'm using the POSIX library.

Thanks,

PS. This question is somewhat related to an earlier question posted here:

Sharing data between master thread and slave thread in interrupt driven environment in C

Was it helpful?

Solution

Instead of having your monitoring thread spin on a flag, it could wait until the interrupt handler provides notification that a thread should be spawned. One way to do this is with a semaphore:

sem_t interrupt_sem;

void interrupt_handler(void)
{
  sem_post(&interrupt_sem);
}

void monitoring_thread(void)
{
  while(1)
  {
    sem_wait(&interrupt_sem);
    //start the thread here
  }
}

Previously, I had a solution based on a condition variable, but it is unlikely your system would operate correctly if the interrupt handler makes blocking calls. It could cause a deadlock or other undefined behaviors, as the variables in the system may not have consistent values at the time the interrupt takes place.

As pointed out in comments by myself and others, your operating system should provide some kind of interface to explicitly wake up a waiting task. In the code above, we are assuming the monitoring thread is always active in the background.

OTHER TIPS

you can use POSIX semaphore too

you can wait a semaphore that initial value is 0 by a thread that will be blocked by wait

and post this semaphore in your signal handle function

then , thread above will be waked up and do things you want(create thread)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top