namespace CompletionCondition
{
    public class SharedState
    {
        public int state;
        public SharedState(int state)
        {
            this.state = state;
        }
    }
    public class Program
    {
        public static void Main()
        {
            SharedState state = new SharedState(0);
            Thread[] thread = new Thread[5];
            for (int i = 0; i < 5; i++)
            {
                thread[i] = new Thread(new ParameterizedThreadStart(ThreadMain));
                thread[i].Start(state);
            }
            for (int i = 0; i < 5; i++)
            {
                thread[i].Join();
            }
            Console.WriteLine("Summarized {0}", state.state);
            Console.Read();
        }
        public static void ThreadMain(object o)
        {
            SharedState state = o as SharedState;
            for (int i = 0; i < 10000; i++)
            {
                state.state++;
            }
        }
    }
}为什么创建的5个进程同时共用了Main()中创建的SharedState的对象State。 但是为什么没有出现中的竞争呢?  

解决方案 »

  1.   

               for (int i = 0; i < 10000; i++)
                {
                    state.state++;
                }像这种……很快就完了……而新建立一个线程……很慢……所以……没有争用况且……编译器根本不会“傻”到累加一万次……我觉得这块代码是这样执行的:state.state += 10000;编译器直接这样做了就……所以……你这样测试没有意义……
      

  2.   

    楼主是想测试下有没有竞争么?
    还是...
    加个Lock应该就可以的吧。
      

  3.   


    如果你用单核CPU的机器,是比较难出现竞态(虽然理论上还是会出现的,但线程切换要恰恰发生在特殊点上)。
    而且10000个加法很快,大部分情况用不完一个系统分配的时间片就完成了。
    我在下帖2楼有个测试结果,双核CPU,作加法20万次。在20次测试中只出现了4次竞态。
    Interlocked.Increment(ref currentIndex);