473,836 Members | 2,125 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 2492
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
20743
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
3854
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
2715
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
1272
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 threading activities between 2 or more
5
2085
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
3201
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
5280
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 they both do a Monitor.Pulse to hand of the locked resource back to thread 1. While thread 1 has...
0
987
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 over others in the waiting queue? I need the waiting thread to be the one next in line to acquire the...
13
2684
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
9812
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 usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
10823
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. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10243
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 choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
9359
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7775
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6975
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 into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5642
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 the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5812
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
3
3103
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 effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.