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。 但是为什么没有出现中的竞争呢?
解决方案 »
- 求个c#实现的俄罗斯方块源码
- 关于Dictionary.KeyCollection
- 求DataTable中2行位置互换
- 如何调用Win32API或是.NET Framework Library创建shared folders?
- 求试题
- 用C#编写的聊天软件需要高手更改
- C#窗体操作问题
- <a target="_self" href=Replybbs.aspx?ID=<%response.write(request.querystring("ID"))%> >不能编译,请指点迷津嘛
- 急!!!c#中有没有方法可以设定本地系统时间?使用winapi函数除外.
- 计算列问题,祝大家新年快乐!!
- pocket pc 程序页面显示问题
- C#面试基本概念
{
state.state++;
}像这种……很快就完了……而新建立一个线程……很慢……所以……没有争用况且……编译器根本不会“傻”到累加一万次……我觉得这块代码是这样执行的:state.state += 10000;编译器直接这样做了就……所以……你这样测试没有意义……
还是...
加个Lock应该就可以的吧。
如果你用单核CPU的机器,是比较难出现竞态(虽然理论上还是会出现的,但线程切换要恰恰发生在特殊点上)。
而且10000个加法很快,大部分情况用不完一个系统分配的时间片就完成了。
我在下帖2楼有个测试结果,双核CPU,作加法20万次。在20次测试中只出现了4次竞态。
Interlocked.Increment(ref currentIndex);