【问题标题】:thread concurrently running and output variables线程并发运行并输出变量
【发布时间】:2015-02-26 17:00:21
【问题描述】:

我在 Trace 这个例子中遇到了挑战: 假设我们有两个线程同时运行这两个threads。在下面的代码中,所有线程都访问共享变量a, b, c。运行此代码后c 的预期值为:4,7,6,13,-3,14,1.

任何帮助或想法将达到此输出?

Initialization 
a=4;
b=0;
c=0;

Thread 1
if (a<b) then
    c=b-a;
else
    c=b+a;
endif

Thread 2
b=10;
c=-3;

【问题讨论】:

    标签: c++ multithreading concurrency race-condition critical-section


    【解决方案1】:

    1 的序列(c = b + a 实现为 c = b, c += a):

        (a<b) false  // thread 1 a == 4, b == 0
        else         // thread 1
        c = b + ...  // thread 1 c = b == 0
        b = 10       // thread 2
        c = -3       // thread 2 c = -3
        c = ... + a  // thread 1 c += a == 1
    

    4 的序列

       (a<b) false   // thread 1 a == 4, b == 0
       a + b         // thread 1 sum of 4 + 0 = 4
       b = 10        // thread 2
       c = -3        // thread 2
       c = a + b     // thread 1  c = previously calculated sum of 4
    

    -3 的序列

       ...           // thread 1 runs first
       c = -3        // thread 2, last statement
    

    13 的序列

       ...           // thread 1 is going to calculate c = a, c = b - c
       c = 4         // thread 1 c = a
       b = 10        // thread 2
       c = -3        // thread 2
       c = b - c     // thread 1 c = 10 - (-3) = 13
    

    6 的序列

       b = 10        // thread 2
       c = -3        // thread 2
       (a<b) true    // thread 1
       c = b-a       // thread 1  c = 10 - 4 = 6
    

    14 的序列

       (a<b) false   // thread 1
       b = 10        // thread 2
       c = -3        // thread 2
       c = b+a       // thread 1  c = 10 + 4 = 14
    

    7 的序列(c = b + a 实现为 c = a, c += b):

       (a<b) true    // thread 1
       c = a         // thread 1  c = 4
       b = 10        // thread 2
       c = -3        // thread 2
       c += b        // thread 1  c = -3 + 10 = 7
    

    【讨论】:

    • 亲爱的@rcgldr,我听不懂你的回答!
    • 当编译器通过先执行 c = b,然后执行 c += a 来实现线程 1 的 c = b + a 时发生序列,线程 2 在线程 1 的 c = b 之后更改 b,线程 2 更改c 在 thread1 的 c += a 之前。
    • 我的问题是谁能计算出这个值:4,7,6,13,-3,14,1?
    • 在原始帖子中,您提到您认为 1 是错误的。我假设您认为所有其他情况都可以。您还想知道哪些其他案例?
    • 你知道你很专业,但请考虑我。我知道浪费你宝贵的时间。但事实上我完全混淆了。直到下周我才找到我的助教。如果可能的话,请向我学习所有情况。如果不是请说接受你的回答。我正在寻找你亲切的答复。我认为这个网站对学习新事物非常有用...
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-09
    • 2013-04-12
    • 2015-08-20
    相关资源
    最近更新 更多