Search code examples
c#.netmultithreadingthread-synchronization

Thread synchronization with Monitor.Pulse NOT working as expected


I have two methods, first() and second() and I assigned them to two threads.

Following are my second and first methods

     public void first()
    {
        lock (this)
        {
            Monitor.Wait(this);   

            Console.WriteLine("First");
            Monitor.Pulse(this);
        }
    }

    public void second()
    {
        lock (this)
        {
            //Monitor.Wait(this);
            Console.WriteLine("Second");
            Monitor.Pulse(this);
        }
    }

The problem is on console only "Second" is getting printed. Even though I have Monitor.Pulse() in second() to notify that the control should shift to first() but that aint happening.

I am following msdn following https://msdn.microsoft.com/en-us/library/aa645740(v=vs.71).aspx

Any help will be appreciated for info why the s thread is NOT shifting control to f thread with Monitor.Pulse() in second()

Follwinng is my Main()

        test t = new test();
        test1 t1 = new test1();
        Thread f = new Thread(new ThreadStart(t.first));
        Thread s = new Thread(new ThreadStart(t1.second));
        f.Start();
        s.Start();
        f.Join();
        s.Join();

Solution

  • The producer /consumer example works on one instance of cell. I think you should do the same. The reference to 'this' is different for your 'first' and 'second'.