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++;
}
}
}
This code is in a console application:
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();
Sometime it prints ’99’ and sometime ‘100’, regardless of whether the lock{...} block exists or not. Is there any wrong in my code?
The problem here would be that you’re kicking off the threads and they’re not entirely finished by the time of your call to write output to the console.
The loop starts off i threads, we’ll imagine these as bees going of collecting as work, not all going to the same food source so some take longer to return than others; then, back at the hive, we suddenly say: “Hey, bees, I need a headcount!”, “…1, 2, 3…, only three?” No, some i-3 are still scrounging around outside!
So, the idea is that we must have an indicator of when work is completed, or a homing signal of sorts to get all bees back to the hive for the headcount. This can be done with
Join, or manual state checking (which essentially has you holding out until the last sojourner returns.)