user110036
user110036

Reputation: 261

Semaphore implementation : why is disabling interrupts required along with test-and-set?

Going over this sample semaphore implementations (for SMP systems), I understand the test-and-set is required for multiprocessor atomic checks. However, once we add the atomic checks aren't the disable interrupts redundant ? The disable interrupts, anyway, only offer atomicity over one processor. Addition to the semaphore queue also needs to be protected.

class semaphore {
private int t;
private int count;
private queue q;

public semaphore(int init)
{
    t = 0;
    count = init;
    q = new queue();
}

public void P()
{
    Disable interrupts;
    while (TAS(t) != 0) { /* just spin */ };
    if (count > 0) {
        count--;
        t = 0;
        Enable interrupts;
        return;
    }
    Add process to q;
    t = 0;
    Enable interrupts;
    Redispatch;
}

public V()
{
    Disable interrupts;
    while (TAS(t) != 0) { /* just spin */ };
    if (q == empty) {
        count++;
    } else {
        Remove first process from q;
        Wake it up;
    }
    t = 0;
    Enable interrupts;
}

}

Upvotes: 11

Views: 5163

Answers (1)

Anne Solmssen
Anne Solmssen

Reputation: 156

While it is true that turning interrupts off on one processor is insufficient to guarantee atomic memory access in a multiprocessor system (because, as you mention, threads on other processors can still access shared resources), we turn interrupts off for part of the multiprocessor semaphore implementation because we do not want to be descheduled while we are doing a test and set.

If a thread holding the test and set is descheduled, no other threads can do anything with the semaphore (because its count is protected by that test and set) the thread was using while it's asleep (this is not good). In order to guarantee that this doesn't happen we'll turn interrupts on our processor off while using the test and set.

Upvotes: 14

Related Questions