【问题标题】:Concurrent loads and stores并发加载和存储
【发布时间】:2013-11-13 15:20:08
【问题描述】:

在 C 中我有:

double balance;
void deposit(double amount) 
{balance = balance +amount;}

机器语言:

load R1, balance
load R2, amount
add R1, R2
store R1, balance

如果变量 balance 包含 500 并且两个线程同时运行程序分别存入 300 和 200,这怎么会有问题呢?以及如何使用并发机制使这个过程线程安全?

【问题讨论】:

    标签: c multithreading concurrency system theory


    【解决方案1】:

    并发 101

    Thread 1                  Thread 2
    
    load R1, balance
    load R2, amount           load R1, balance
    add R1, R2                load R2, amount
    store R1, balance         add R1, R2
                              store R1, balance
    

    线程 1 的写入丢失。 (有许多序列可以达到大致相同的结果。)

    您可以通过锁定balance 来修复它,这样只有一个线程或另一个线程可以在加载和存储之间访问它。在序列开始处获取balance 上的互斥体并在结束时释放它。考虑在加载 balance 之前加载 amount 以将互斥体的范围减小到最小。

    【讨论】:

      猜你喜欢
      • 2016-02-26
      • 2011-10-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-06-07
      • 1970-01-01
      相关资源
      最近更新 更多