开发者

Atomic variable Vs. Atomic operation

开发者 https://www.devze.com 2022-12-31 12:19 出处:网络
Lets say I 开发者_Python百科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 operatio

Lets say I 开发者_Python百科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


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号