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
How to count the number of objects present in a web page? How to count the number of radio buttons in a web page?
if i want to give an alert message like "try after sometime" to a web page which is being seen by other person.if a web page is not seen by anyone then it should display otherwise it show a display a message stating that other person is viewing so try after some time........how can i implement this.
What is the application pool?
What is http protocol and how it works?
What is asp.net mvc? : asp.net mvc
What symbol specifies the beginning of a query string?
How do you open a page in a new window?
What is ipostback?
What is syntax code to send email from an asp.net application?
What is actually returned from server to the browser when a browser requests an .aspx file and the file is displayed?
what is publisher?
Explain the namespace classes used in asp.net mvc? : asp.net mvc
Types of instancing properties and explain each. Tell the difference between multiuse,singleuse and globalmultiuse and which is default ?
What is the page life cycle in asp.net?
Are xaml file compiled or built on runtime?