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


Please Help Members By Posting Answers For Below Questions

What is csrf attack in asp.net?

515


Define static constructor?

552


If you want to write your own dot net language, what steps you will you take care?

520


Explain the difference between singleton and single call?

532


What is the file through which you can customize your asp.net application?

541






What are the different types of cookies in asp.net?

518


Explain how can we inherit a static variable?

520


What are sql joins?

565


Explain about ASP.NET?

628


Describe the .net base class library.

527


What is http protocol and how it works?

525


14. What are your Future Plans for Swatz Oils GROUP U.K?

1717


What is base class of .net?

531


What is a user session?

497


Define dll hell?

625