views:

177

answers:

1

Hi,

Lets say I have two shared variables - a and b - that are related to each other. When multiple applications share these shared variables, access to them needs to be an atomic operation, otherwise the relation may break. So to ensure mutual exclusion, I'll put their modification under a critical section protected by lock.

critical_code
{
    P(mutex)
    a := something
    b := something
    V(mutex)
}

Lets say my hardware/OS/compiler supports atomic variables. Then I modified my above code as follows.

code
{
    atomic a := something
    atomic b := something
}

Can this code ensure mutual exclusion, when accessed by multiple applications?

Sincerely,
Srinivas Nayak

+2  A: 

No, you still need a critical section. While update of each variable is atomic, this still doesn't warrant against situations when one process has only midified one variable but the other is already reading the inconsistent state.

You only rely on atomic variables when it's enough to know that every one write and every one read is atomic - i.e. you're already happy if you know that when one process is updating the variable the other will not read a partially changed variable.

So atomic variable is atomic per one variable, not per set of variables.

sharptooth