473,569 Members | 2,813 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Monitor.Pulse question

Hi, Below is a hacked up version of an example I found on MSDN. My only
change was to add a third thread and some Sleeps. That's where my
question(s) comes in.
In the original it seems to work because Thread1 waits on Thread2 and
vice versa, although I can't quite see how.
Disabling Thread3 and leaving the sleep in works fine, processing is
nicely throttled. Activating Thread3 and we enter a world of pain. I
don't understand what the first Pulse is doing in Thread2, I think I
understand the second one, and the purpose of the Wait, although how
it's reached inside the Lock statement confuses me.

Here's the code,it should work pasted verbatim into a console app. If
someone has a simple explanation of what Pulse is supposed to do, and
how the various competing lock statements interact, or even how to make
the code below function (ie Thread1 pumps out stuff, Thread2 and 3
consume it when they can), then I'll be a happy bunny.

Thanks.

using System;
using System.Threadin g;
using System.Collecti ons;

namespace MonitorCS1
{
class MonitorSample
{
const int MAX_LOOP_TIME = 1000;
Queue m_smplQueue;
Random r = new Random(1);

public MonitorSample()
{
m_smplQueue = new Queue();
}
public void FirstThread()
{
int counter = 0;
lock(m_smplQueu e)
{
while(counter < MAX_LOOP_TIME)
{
//Wait, if the queue is busy.
Monitor.Wait(m_ smplQueue);
//Push one element.
m_smplQueue.Enq ueue(counter);
//Release the waiting thread.
Monitor.Pulse(m _smplQueue);

counter++;
}
}
}
public void SecondThread()
{
lock(m_smplQueu e)
{
//Release the waiting thread.
Monitor.Pulse(m _smplQueue);
//Wait in the loop, while the queue is busy.
//Exit on the time-out when the first thread stops.
while(Monitor.W ait(m_smplQueue ,1000))
{
//Pop the first element.
int counter = (int)m_smplQueu e.Dequeue();
//Print the first element.
Console.WriteLi ne("Second " + counter.ToStrin g());
//Release the waiting thread.
Monitor.Pulse(m _smplQueue);
Thread.Sleep(r. Next(20));
}
}

}
public void ThirdThread()
{
lock(m_smplQueu e)
{
//Release the waiting thread.
Monitor.Pulse(m _smplQueue);
//Wait in the loop, while the queue is busy.
//Exit on the time-out when the first thread stops.
while(Monitor.W ait(m_smplQueue ,1000))
{
//Pop the first element.
int counter = (int)m_smplQueu e.Dequeue();
//Print the first element.
Console.WriteLi ne("Third " + counter.ToStrin g());
//Release the waiting thread.
Monitor.Pulse(m _smplQueue);
Thread.Sleep(r. Next(20));
}
}
}
//Return the number of queue elements.
public int GetQueueCount()
{
return m_smplQueue.Cou nt;
}

static void Main(string[] args)
{
//Create the MonitorSample object.
MonitorSample test = new MonitorSample() ;
//Create the first thread.
Thread tFirst = new Thread(new ThreadStart(tes t.FirstThread)) ;
//Create the second thread.
Thread tSecond = new Thread(new ThreadStart(tes t.SecondThread) );

Thread tThird = new Thread(new ThreadStart(tes t.ThirdThread)) ;
//Start threads.
tFirst.Start();
tSecond.Start() ;
tThird.Start();
//wait to the end of the two threads
tFirst.Join();
tSecond.Join();
tThird.Join();
//Print the number of queue elements.
Console.WriteLi ne("Queue Count = " +
test.GetQueueCo unt().ToString( ));
}
}
}

Nov 14 '06 #1
2 2482
Solved it... Sort of,Replacing the While in Thread2 and 3 with:

while(Monitor.W ait(m_smplQueue ))
{
if(m_smplQueue. Count>0)
{
//Pop the first element.
int counter = (int)m_smplQueu e.Dequeue();
//Print the first element.
Console.WriteLi ne("Third " + counter.ToStrin g());
//Release the waiting thread.
}
Monitor.Pulse(m _smplQueue);
Thread.Sleep(r. Next(50));
}

Solves the problem, I still don't know what the first Pulse is for
though in Threads 2 and 3.
Thanks

Nov 14 '06 #2
Just read this:
http://pluralsight.com/blogs/mike/ar...2/13/3905.aspx which
strangely cleared up my confusion. I'd already figured out I had picked
the wrong direction to expand the demo code in, I was trying for
concurrency instead of serialisation. As soon as I saw the above it all
clicked into place :)

Nov 14 '06 #3

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

4
20724
by: Vinay C | last post by:
Hi, Can anyone clear me that, when should we use go for mutex, and in which situation should we opt for monitor, lock, semaphone and other objects, in a multithreaded application for synchronization ? Thanks
5
3838
by: bughunter | last post by:
Hi, Consider this code: ---- Monitor.Pulse(oLock); Monitor.Exit(oLock); ---- If a thread was waiting on oLock then will the current thread
25
2679
by: vooose | last post by:
Suppose execution of a particular thread T1 hits Monitor.Enter(obj); //critical section and blocks at the first line. (ie someone else is in the critical section) Now suppose more threads T2, T3... try to enter the critical section and are blocked. What is the order that the threads get to enter the critical section?
1
1263
by: Mike | last post by:
I have to ask a stupid question regarding Monitor. Wait() and Pulse() make be used to wait for and signal events in a given thread. However, neither can be used until calling within a synchronized block between calls to Enter() and Exit(). Am I missing something when I say that it seems useless to use this facility to synchronize...
5
2071
by: Ken Varn | last post by:
If I have a value type such as int that I want to protect in a multi-threaded situation, Is it safe to use Monitor::Enter(__box(value))? I am thinking that a different object pointer is generated each time and thus the protection is not insured. Is this true or not? Example: public _gc class MyClass { int Value;
4
3176
by: Charles Law | last post by:
I've been using monitors a bit lately (some of you may have heard ;-) ) and then up pop Manual and AutoResetEvents , and they look for all the world like the same thing. Are they interchangeable, or when should I use one over the other? TIA Charles
12
5250
by: Perecli Manole | last post by:
I am having some strange thread synchronization problems that require me to better understand the intricacies of Monitor.Wait/Pulse. I have 3 threads. Thread 1 does a Monitor.Wait in a SyncLock block protecting a resource. Thread 2 and 3 also have a SyncLock block protecting the same resource and after executing some code in their blocks...
0
975
by: Perecli Manole | last post by:
Background: Upon receiving a Monitor.Pulse, the waiting thread is moved to the ready queue. When the thread that invoked Monitor.Pulse releases the lock, the next thread in the ready queue (which is not necessarily the thread that was pulsed) acquires the lock. How can a ensure that the waiting thread gets priority in acquiring the lock...
13
2663
by: AliRezaGoogle | last post by:
Dear Members, I have a problem in the concepts of Monit.Enter and Monitor.Exit (Before everything I should say that I know how to solve this problem by using Monitor.Wait and I do not need a solution. But this question sticks to my head as a conceptual problem) Suppose there are two threads T1, T2 running concurrently:
0
7703
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main...
0
7926
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. ...
1
7679
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For...
0
7983
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the...
0
5223
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert...
0
3657
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in...
0
3647
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
1228
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
946
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.