Write a standard lock() plus double check to create a
critical section around a variable access?



Write a standard lock() plus double check to create a critical section around a variable access?..

Answer / 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

More ASP.NET Interview Questions

When during the page processing cycle is ViewState available?

1 Answers  


Define a static class?

0 Answers  


What is meant by web application?

0 Answers  


What Are The Difference Between AutoEventWireup="true" and AutoEventWireup="False"

12 Answers   Phoenix Technologies,


Explain the asp.net session state modes.

0 Answers  






Why is xap important?

0 Answers  


What is WCF

4 Answers  


how can u create the blog in asp.net with C#?what is the data type u will use to store in sql server?

0 Answers   IBM,


there is two functions function a and function b like fun a(){.... ..... } fun b() { } in function b i write the coding to add two numbers and i need to dispaly the sum result in function a with out using global variable. how we do?

1 Answers  


How u refer webservices?

0 Answers   Microsoft,


Where is session data stored in asp net?

0 Answers  


To make Cache item dependent on a file,directory or other cached item ,you should create an instance of which clause?

1 Answers  


Categories