Cheiron
Cheiron

Reputation: 3736

Possible deadlock situation: interrupt and mutex

I have this C++ program, which eventually falls apart in two threads. One thread waits for an interrupt, and if it happens it will increment a counter:

void reactInterrupt(){
    counter_lock.lock();
    std::cout<< ++counter;
    counter_lock.unlock();
}

The interrupt code comes from wiringPi There is also the seconds thread, which sleeps for x seconds and when it wakes up, it does the following:

//blaaah
    int coutercopy;
    counter_lock.lock();
    countercopy = counter;
    counter = 0;
    counter_lock.unlock();
//more blaah

Now I am extremely curious: what would happen if the mutex was being locked by the second thread on the moment an interrupt would happen. How deep does the interrupt go? Does it completely lock everything while it is trying to finish the reactInterrupt() code? Because if that is the case, I see an (extremely rare) deadlock situation where the CPU would just wait indefenitly for the mutex to become unlocked. Or does the interrupt merely schedule the method for execution, which would only mean the the method is being added to the list of things the CPU has to do? In that case the method would just wait for the mutex to become free, which I would think is much nicer.

Upvotes: 0

Views: 941

Answers (1)

Captain Obvlious
Captain Obvlious

Reputation: 20063

Interrupt service routines in wiringPi are non-blocking and will not prevent the rest of your program from executing. When you install an ISR wiringPi starts a separate polling thread that calls waitForInterrupt to wait for the IRQ line to trigger. When an IRQ is triggered it calls the provided service routine in the context of the polling thread.

From wiringPi.c

static void *interruptHandler (void *arg)
{
    int myPin ;

    (void)piHiPri (55) ;  // Only effective if we run as root

    myPin   = pinPass ;
    pinPass = -1 ;

    for (;;)
        if (waitForInterrupt (myPin, -1) > 0)
            isrFunctions [myPin] () ;

    return NULL ;
}

Upvotes: 1

Related Questions