Write a standard lock() plus double check to create a
critical section around a variable access?
Answer Posted / debmalya kundu
using System;
using System.Text;
using System.Threading;
namespace thread01
{
public class Counter
{
private int _count=0;
private int _even=0;
public int Count { get { return _count; } }
public int EvenCount { get { return _even; } }
private Object theLock = new Object();
public void UpdateCount()
{
lock (theLock)
{
_count = _count + 1;
if (Count % 2 == 0) // An even number
{
_even += 1;
}
}
}
}
class Program
{
static void Main(string[] args)
{
Counter count = new Counter();
ParameterizedThreadStart starter = new
ParameterizedThreadStart(Program.UpdateCount);
Thread[] threads = new Thread[10];
for (int x = 0; x < 10; ++x)
{
threads[x] = new Thread(starter);
threads[x].Start(count);
}
for (int y = 0; y < 10; ++y)
{
threads[y].Join();
}
Console.WriteLine("Total: {0} - Even: {1}",
count.Count,count.EvenCount);
Console.ReadKey();
Console.ReadKey();
}
static void UpdateCount(object param)
{
Counter count = (Counter)param;
for (int z = 1; z <= 100000; ++z)
{
count.UpdateCount();
}
}
}
}
| Is This Answer Correct ? | 3 Yes | 0 No |
Post New Answer View All Answers
What is sdlc process?
Distinguish between Server-side and Client-side code with its functionality?
How can we identify that the Page is Post Back?
What is session in asp.net?
What is the use of data set in asp.net?
What language is asp.net written in?
What are the different kinds of assemblies?
What is difference between datalist and gridview?
What is the difference between session and application?
Asp pages that worked pefectly on windows 2000 server and iis 5.0 do not work on windows 2003 server with iis 6.0. Asp.net pages work fine. Why?
What websites use asp.net?
What is Forms Authentication in ASP.NET?
can we remote debug applications with the remote debugger installed with vs.net 2002, with vs.net 2003?
What is web api vs wcf?
where can i gather the materials for MCP certification