【发布时间】:2011-09-08 10:09:03
【问题描述】:
public class ThreadInteroperateWithLock
{
private int m_count;
private object m_synLock;
public ThreadInteroperateWithLock()
{
m_count = 0;
m_synLock = new object();
}
public int Count { get { return m_count; } }
public void Add()
{
//just simulate some work
int temp=0;
for (int i = 0; i < 10000; i++)
{
temp++;
}
//really job
lock (m_synLock)
{
m_count++;
}
}
}
此代码在控制台应用程序中:
ThreadInteroperateWithLock ope = new ThreadInteroperateWithLock();
Thread[] threadArray = new Thread[100];
for (int i = 0; i < 100; i++)
{
Thread thread = new Thread(new ThreadStart(ope.Add));
thread.IsBackground = false;
threadArray[i] = thread;
}
for (int i = 0; i < 100; i++)
{
threadArray[i].Start();
}
Console.WriteLine(ope.Count);
Console.ReadKey();
无论lock{...} 块是否存在,它有时会打印“99”,有时会打印“100”。我的代码有问题吗?
【问题讨论】:
标签: c# thread-safety