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 are the types of session in asp.net?

701


What are the validation controls available in ASP.NET?

719


State differences between MVC and WebAPI

816


What is asp.net response object?

774


How is it possible for .NET to support many languages?

490


What is different in .net 1.1 and .net 2.0?

762


Why do we use datasource in asp.net?

704


Where do the cookie state and session state information be stored?

697


What is app_code folder in asp net?

747


Do cookies store passwords?

680


Just by seeing the signature of the bean how can you specify whether it is a stateful or stateless session bean?

738


What is the function of the ViewState property?

811


How do you identify that the page is postback?

711


Explain asp.net page life cycle?

830


Does web services support data reader like pom project?

696