English 中文(简体)
多种透镜加固时,共同变量的最低和最大可能价值
原标题:Minimum and maximum possible value of a shared variable when incremented by multiple threads

I have a global shared variable and that is being updated 5 times by each of the 5 threads spawned. As per my understanding the increment operation is consisting of 3 instructions

load  reg, M
inc reg
store reg, M

因此,我要问,在这种情形下,在5条深线中任意搭桥会带来最大和最低价值。

So according to me the maximum value will be 25 ( I am 100% sure that it can be more than 25) and the minimum value is 5. But I am not so sure on minimum value. Can it be less that 5 in some arbitrary interleaving ? Any inputs will be greatly appreciated.

/* Global Variable */
int var = 0;

/* Thread  function */
void thread_func()
{
     for(int c = 0; c < 5; c++)
             var++;
}
问题回答

Given your definition of increment, I agree with your max of 25.

然而,我认为,在以下情况下,这名人可能是2人。 我点名的是A、B、C、D和E。

  1. A loads 0
  2. C, D, E run to completion
  3. B runs through 4 of its 5 iterations.
  4. A increments 0 to 1 and stores the result (1).
  5. B loads 1
  6. A runs to completion
  7. B increments 1 to 2 and stores 2.

如果我采用jtdubs的相同逻辑,那么在以下情况下,最低价值应为1。

让我们使用与A、B、C、D和E一样的5条镜头。

  1. A loads 0
  2. B, C, D, E run to completion and incremented to maximum value 20 (5 increments by each of 4 threads).
  3. A increments 0 to 1 and store the result 1.

我同意至少2项(而不是1项)。

The minimum equals 1 solution ignores the fact that A still hasn t run to completion after it stores 1 in the shared memory. With no other thread left to "interfere", thread A must still run through the remaining 4 iterations ending with the result 5.

What the minimum of 2 solution enables is an end-game between the two remaining threads A and B, after all other threads have finished running, leading to the minimum possible outcome. B "wastes" 4 iterations only to load 1 again, increment it and store 2 after A has run to completion.





相关问题
Silverlight, Updating the UI during processing

I have a simple silverlight multifile upload application, and i want to provide the user with some feedback, right now its only in a test phase and i dont have the webservice. Somehow i cant get the ...

Is reading from an XmlDocument object thread safe?

I was wondering if i could safely read from an XmlDocument object using SelectNodes() and SelectSingleNode() from multiple threads with no problems. MSDN says that they are not guaranteed to be ...

Terminating a thread gracefully not using TerminateThread()

My application creates a thread and that runs in the background all the time. I can only terminate the thread manually, not from within the thread callback function. At the moment I am using ...

热门标签