I don't understand monitor.wait and monitor.pulse

Posted on 2008-10-28
Last Modified: 2008-10-29
I'm trying to understand this method to syncronizate in multithreading but I don't understand them.
I have found the following example but I dont' understand it.

I don't understand how it use the Queue as a lock object.

I think wait method over a lock variable wait until another process pulse that lock variable.

Could you explain me this method because it is hard to me understanding it. I have been working with VB6 and now I'm learning VB 2008 and it is very hard.

Another thing, Do you know a good book of VB2008 I could buy in Spain?

Imports System

Imports System.Threading

Imports System.Collections

Namespace MonitorCS1

   Class MonitorSample

      Private MAX_LOOP_TIME As Integer = 1000

      Private m_smplQueue As Queue



      Public Sub New()

         m_smplQueue = New Queue()

      End Sub 'New


      Public Sub FirstThread()

         Dim counter As Integer = 0

         SyncLock m_smplQueue

            While counter < MAX_LOOP_TIME

               'Wait, if the queue is busy.


               'Push one element.


               'Release the waiting thread.



               counter += 1

            End While

         End SyncLock

      End Sub 'FirstThread


      Public Sub SecondThread()

         SyncLock m_smplQueue

            'Release the waiting thread.


            'Wait in the loop while the queue is busy.

            'Exit on the time-out when the first thread stops. 

            While Monitor.Wait(m_smplQueue, 1000)

               'Pop the first element.

               Dim counter As Integer = CInt(m_smplQueue.Dequeue())

               'Print the first element.


               'Release the waiting thread.


            End While

         End SyncLock

      End Sub 'SecondThread


      'Return the number of queue elements.

      Public Function GetQueueCount() As Integer

         Return m_smplQueue.Count

      End Function 'GetQueueCount


      Public Shared Sub Main(args() As String)

         'Create the MonitorSample object.

         Dim test As New MonitorSample()

         'Create the first thread.

         Dim tFirst As New Thread(AddressOf test.FirstThread)

         'Create the second thread.

         Dim tSecond As New Thread(AddressOf test.SecondThread)

         'Start threads.



         'wait to the end of the two threads



         'Print the number of queue elements.

         Console.WriteLine(("Queue Count = " + test.GetQueueCount().ToString()))

      End Sub 'Main

   End Class 'MonitorSample

End Namespace 'MonitorCS1

Open in new window

Question by:jeaguado
  • 2
LVL 59

Expert Comment

by:Kevin Cross
ID: 22827271
You are creating lock on the object that you whose changes/reads you want to make thread safe.  Meaning, you lock m_smplQueue while it is being incremented so that you don't get two threads trying to increment from 3 to 4 as an example.  You want 3 to go to 4 in thread 1 then thread 2 to further increment to 5.  Likewise when reading, you don't want to read 3 and act on that amount of data in m_smplQueue when really there is about to be 4.

Not sure if that made it any clearer, but that is my attempt.

It is like application lock when setting application variable in VB6 (ASP).  You could have technically locked the entire MonitorSample instance (application) until you were done changing the value of its member m_smplQueue but that would then also prevent you from changing value in another member like m_smplQueue2.

Author Comment

ID: 22829240
In this example, Could I use another object only defined to be used by wait and pulse?
Dim m_objLock as object

Is better using monitor.enter than syncLock?
LVL 59

Accepted Solution

Kevin Cross earned 500 total points
ID: 22830076
Should have same effect.  The point is you are synchronizing the access to m_smplQueue.  What the latter will do in cases where you don't want to lock while reading, you can use special locking objects that allow write once / read multiple type of locks.

Not sure if I would call it better, but a lot of personal style goes into programming sometimes and being a developer in multiple syntaxes, I tend to use SyncLock because it is close in concept to synchronized { } blocks I use in other languages.

Here is probably better explaination:

Featured Post

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
Code enhancement 5 22
Check if number is currency 15 31
Get String split 5 48
Definitions and default visual studio colors 5 58
Since .Net 2.0, Visual Basic has made it easy to create a splash screen and set it via the "Splash Screen" drop down in the Project Properties.  A splash screen set in this manner is automatically created, displayed and closed by the framework itsel…
Introduction As chip makers focus on adding processor cores over increasing clock speed, developers need to utilize the features of modern CPUs.  One of the ways we can do this is by implementing parallel algorithms in our software.   One recent…
Windows 10 is mostly good. However the one thing that annoys me is how many clicks you have to do to dial a VPN connection. You have to go to settings from the start menu, (2 clicks), Network and Internet (1 click), Click VPN (another click) then fi…
With the power of JIRA, there's an unlimited number of ways you can customize it, use it and benefit from it. With that in mind, there's bound to be things that I wasn't able to cover in this course. With this summary we'll look at some places to go…

920 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

13 Experts available now in Live!

Get 1:1 Help Now