Thread on C#

Hello, Every One.. im having a problem with Thread cuncurrency..im using Monitor to deal with this problem but the monitor some times let 2 Thread access the same resource together. Whats wrong with my code.

Many Thanks

The idea is Creating 10 Threads that each Thread try to access the same Singleton Object.
Some time a get the output 10,9,10,9,8,9,10,10..

MortarelloAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

MortarelloAuthor Commented:
Sorry o forgot to post my code ..

Tks.
---------------------------------------------------------------------------------------------------------

class Program
    {
        static object obj = new object();
        static void Main(string args)
        {

            List<Thread> Tlist = new List<Thread>();

            for (int i = 0; i < 10; i++)
            {
                Tlist.Add(new Thread(new DataBase().Add));
                Tlist.Start();
            }

            for (int i = 0; i < 10; i++)
            {
                Tlist
.Join();  
            }

            Console.WriteLine("Total sum is {0}", Value.Instance().sum);

        }
    }
------------------------------------------------------------------------------------------
public class DataBase
    {
        public void Add()
        {
            Value.Instance().AddOne();
        }

        public int GetSum()
        {
            return Value.Instance().sum;    
        }
    }

-------------------------------------------------------------------------
public class Value
    {
        static Value _instance;
        public static Value Instance()
        {
            if (_instance == null)
                _instance = new Value();
            return _instance;
        }

        public volatile int sum = 0;
        Random r = new Random();
        private static readonly object obj = new object();
        public void AddOne()
        {
            lock (obj)
            {
                Console.WriteLine("Im Writing..{0}", Thread.CurrentThread.ManagedThreadId);
                var temp = sum;
                Console.WriteLine("B - {0}", temp);
                temp++;
                Thread.Sleep(50);
                sum = temp;
                Console.WriteLine("A - {0}", sum);
                Console.WriteLine("Im Writing..Done");
                Monitor.Pulse(obj);
            }
        }
    }
0
käµfm³d 👽Commented:
I'm curious:  You are using Monitor.Pulse() to signal waiting threads, but why are you using lock instead of Monitor.Enter() or Monitor.TryEnter() to acquire the lock?
0
MortarelloAuthor Commented:
Hi Kaufmed...I saw  in one example, that when you use lock statement , C# compiler implement for you Monitor.Enter() and Monitor.Exit(). Just less code to type.

lock (obj_lock)
{

}

C# Compiler Make

Try
    Monitor.Enter(Obj_lock)
finally
    Monitor.Exit(Obj_lock)



0
Cloud Class® Course: Microsoft Office 2010

This course will introduce you to the interfaces and features of Microsoft Office 2010 Word, Excel, PowerPoint, Outlook, and Access. You will learn about the features that are shared between all products in the Office suite, as well as the new features that are product specific.

MortarelloAuthor Commented:
Do i need to lock 2 places or just one. Cos i add lock statement on that code below and now works !!!
Am I Right ?

Many Tks !!

private static readonly object obj2 = new object();
public static Value Instance()
        {
            lock (obj2)
            {
                if (_instance == null)
                    _instance = new Value();
                return _instance;
            }
0
käµfm³d 👽Commented:
Actually, disregard my previous question. I was thinking something different.
0
tpaynCommented:
Hi,

you on the right track with your revised code. Please check out this article for examples of creating a thread safe Singleton pattern:

http://csharpindepth.com/Articles/General/Singleton.aspx
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
MortarelloAuthor Commented:
Tks
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
.NET Programming

From novice to tech pro — start learning today.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.