English 中文(简体)
证明职位削减不是原样...... FAIL
原标题:Demonstrating that post decrement is not atomic... FAIL

I was trying out a code sample from this book that should demonstrate that the post decrement operator is not atomic. The code is as I have entered it into LinqPad.

void Main() {
  var count = 0;
  do {
    _x = 10000;
    for (int i = 0; i < 100; i++) {
      new Thread(Go).Start();
    }
    Thread.Sleep(1000);

    Console.WriteLine("Try "+ count);
    count++;
  } while (_x == 0);
  Console.WriteLine(_x);
}

int _x = 10000;
void Go() { for (int i = 0; i < 100; i++) _x--; }

想法是,在不设锁的多个环线上同时进行增减<条码>_x,否则,当所有胎面均已完结时,可产生<条码>-x值。

My problem is that no matter how long I seem to try I always get 0 as a result. I have run the code on two different computers (both Windows 7) and two different versions of .NET and both give me the same result.

What am I missing here?

最佳回答

在<代码>上,我增加了100 000个接口。 Go as Lasse V. Karlsen has recommended. 如今,该法典在第一次审判中发挥了预期的作用。 我也把铺设点移出路面,并像Henk Holterman所建议的那样,减少了read。

void Main()
{
    var count = 0;
    do {
    _x = 1000000;
    var threads = Enumerable.Range(0,10).Select (_ => new Thread(Go)).ToList();

    foreach (var t in threads)
    {
        t.Start();
    }

    Thread.Sleep(1000);
    Console.WriteLine("Try "+ count);
    count++;
    } while (_x == 0);
    Console.WriteLine(_x);
}

int _x;
void Go() { for (int i = 0; i < 100000; i++) _x--; }

该法典现在按预期运作。

问题回答

暂无回答




相关问题
Anyone feel like passing it forward?

I m the only developer in my company, and am getting along well as an autodidact, but I know I m missing out on the education one gets from working with and having code reviewed by more senior devs. ...

NSArray s, Primitive types and Boxing Oh My!

I m pretty new to the Objective-C world and I have a long history with .net/C# so naturally I m inclined to use my C# wits. Now here s the question: I feel really inclined to create some type of ...

C# Marshal / Pinvoke CBitmap?

I cannot figure out how to marshal a C++ CBitmap to a C# Bitmap or Image class. My import looks like this: [DllImport(@"test.dll", CharSet = CharSet.Unicode)] public static extern IntPtr ...

How to Use Ghostscript DLL to convert PDF to PDF/A

How to user GhostScript DLL to convert PDF to PDF/A. I know I kind of have to call the exported function of gsdll32.dll whose name is gsapi_init_with_args, but how do i pass the right arguments? BTW, ...

Linqy no matchy

Maybe it s something I m doing wrong. I m just learning Linq because I m bored. And so far so good. I made a little program and it basically just outputs all matches (foreach) into a label control. ...

热门标签