473,749 Members | 2,451 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

threading

I have a background worker thread that receives queued work items and
processes them. How do I make this background thread go in a sleep state
while the queue is empty and then wake back up as soon as there are work
items to be performed?

To much processor time is being wasted right now checking an empty queue in
a loop.

Thanks
Perry
Nov 20 '05 #1
4 2507
"Perecli Manole" <Pe*****@dslext reme.com> schrieb
I have a background worker thread that receives queued work items
and processes them. How do I make this background thread go in a
sleep state while the queue is empty and then wake back up as soon as
there are work items to be performed?

To much processor time is being wasted right now checking an empty
queue in a loop.


Can you add Thread.Sleep(10 0) inside the loop?
--
Armin

Nov 20 '05 #2
Perecli,
In addition to Armin's suggestion. I normally use a
System.Threadin g.AutoResetEven t along with the queue. Depending on the
parameters you pass to the AutoResetEvent. WaitOne method, the background
thread will sleep indefinitely waiting for the event to be signaled.

The background thread has two loops. The outer loop does an
AutoResetEvent. WaitOne waiting for the event to be signaled. When the event
is signaled the background thread has an inner loop processing each item in
the queue.

When other threads put work items into the queue they Set the above
AutoResetEvent, letting the background thread know there is at least one
item in the queue.

Normally I put the Thread, the AutoResetEvent, the Queue and the padlock for
the Queue into a single class that represents the "Worker". Encapsulating
the above into clean type safe methods.

Hope this helps
Jay

"Perecli Manole" <Pe*****@dslext reme.com> wrote in message
news:Ov******** ******@tk2msftn gp13.phx.gbl...
I have a background worker thread that receives queued work items and
processes them. How do I make this background thread go in a sleep state
while the queue is empty and then wake back up as soon as there are work
items to be performed?

To much processor time is being wasted right now checking an empty queue in a loop.

Thanks
Perry

Nov 20 '05 #3
Hi Perry,

You'd have your Thread sleep when it has finished. Whenever the Queue
receives another Job, it would check the Thread. If it's asleep, you can send
an interrupt. This will cause an Exception which must be caught. [Don't send
the Interrupt if the Thread is not asleep - the Interrupt will hang around
until it <does> go to sleep and then wake it up immediately!!]

Something like the following:

Regards,
Fergus

<code>
In Queue:
oThread As Thread

Sub NewJob (..)
'Add Job to Queue
: : :
If oThread.ThreadS tate = ThreadState.Wai tSleepJoin Then
oThread.Interru pt 'Hey!! Sleepy Head! - I've a job for you.
End If
End Sub

Sub FinishTheJobAnd GoHome(..)
While oThread.ThreadS tate <> ThreadState.Wai tSleepJoin
Thread.Sleep (SomeDelay)
End While
oThread.Abort.
oThread.Join.
End Sub

In Worker
Try
Do
'Busy, busy
: : :
If NoMoreJobs Then
'Done for now
Try
Thread.Sleep (Inifinite) 'ZZZzzzz....
Catch e As ThreadInterrupt edException
'Yawn, .. streeeetch,... better get back to work.
End Try
Loop
Catch e As ThreadAbortExce ption
'Hurray - knocking off time!!
End Try
</code>
Nov 20 '05 #4
It seems like the AutoResetEvent is the best approach.

I don't understand the padlock element you speak of.
Right now I have something like this but want to get rid of Sleep():

Public Sub SubmitCmd(ByVal objCommand As ICmdExecute)
If Not m_objBgThread Is Nothing Then
SyncLock m_objCmdQueue.S yncRoot
m_objCmdQueue.E nqueue(objComma nd)
End SyncLock
End If
End Sub

Private Sub BackgroundThrea d()
Dim objCommand As ICmdExecute

While True
'dequeue all available commands
Do
SyncLock m_objCmdQueue.S yncRoot
If m_objCmdQueue.C ount > 0 Then
objCommand = m_objCmdQueue.D equeue()
End If
End SyncLock

If objCommand Is Nothing Then
Exit Do
Else
objCommand.Exec ute()
objCommand = Nothing
End If
Loop

Thread.Sleep(50 ) 'prevents hoggin up all the CPU's time
End While
End Sub

Should the AutoResetEvent. Set be within the synclock block or out?
What if the AutoResetEvent. Set is executed right before the background
thread is about to call AutoResetEvent. WaitOne? This could halt the
background thread indefinitely even though there are queued items.

Thanks
Perry

"Jay B. Harlow [MVP - Outlook]" <Ja********@ema il.msn.com> wrote in message
news:eL******** ******@TK2MSFTN GP10.phx.gbl...
Perecli,
In addition to Armin's suggestion. I normally use a
System.Threadin g.AutoResetEven t along with the queue. Depending on the
parameters you pass to the AutoResetEvent. WaitOne method, the background
thread will sleep indefinitely waiting for the event to be signaled.

The background thread has two loops. The outer loop does an
AutoResetEvent. WaitOne waiting for the event to be signaled. When the event is signaled the background thread has an inner loop processing each item in the queue.

When other threads put work items into the queue they Set the above
AutoResetEvent, letting the background thread know there is at least one
item in the queue.

Normally I put the Thread, the AutoResetEvent, the Queue and the padlock for the Queue into a single class that represents the "Worker". Encapsulating
the above into clean type safe methods.

Hope this helps
Jay

"Perecli Manole" <Pe*****@dslext reme.com> wrote in message
news:Ov******** ******@tk2msftn gp13.phx.gbl...
I have a background worker thread that receives queued work items and
processes them. How do I make this background thread go in a sleep state
while the queue is empty and then wake back up as soon as there are work
items to be performed?

To much processor time is being wasted right now checking an empty queue

in
a loop.

Thanks
Perry


Nov 20 '05 #5

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

Similar topics

65
6748
by: Anthony_Barker | last post by:
I have been reading a book about the evolution of the Basic programming language. The author states that Basic - particularly Microsoft's version is full of compromises which crept in along the language's 30+ year evolution. What to you think python largest compromises are? The three that come to my mind are significant whitespace, dynamic typing, and that it is interpreted - not compiled. These three put python under fire and cause...
2
2982
by: Egor Bolonev | last post by:
hi all my program terminates with error i dont know why it tells 'TypeError: run() takes exactly 1 argument (10 given)' =program==================== import os, os.path, threading, sys def get_all_files(path): """return all files of folder path, scan with subfolders
77
5373
by: Jon Skeet [C# MVP] | last post by:
Please excuse the cross-post - I'm pretty sure I've had interest in the article on all the groups this is posted to. I've finally managed to finish my article on multi-threading - at least for the moment. I'd be *very* grateful if people with any interest in multi-threading would read it (even just bits of it - it's somewhat long to go through the whole thing!) to check for accuracy, effectiveness of examples, etc. Feel free to mail...
6
555
by: CK | last post by:
I have the following code in a windows service, when I start the windows service process1 and process2 work fine , but final process (3) doesnt get called. i stop and restart the windows service and the final process(3) gets called. what am I doing wrong with the threading? by the way Directory.GetFiles(IncomingXMLPath1).Length is some global outcome from process 1. Thanks 1)
2
2246
by: Vjay77 | last post by:
In this code: Private Sub downloadBtn_Click(ByVal sender As Object, ByVal e As System.EventArgs) If Not (Me.downloadUrlTextBox.Text = "") Then Me.outputGroupBox.Enabled = True Me.bytesDownloadedTextBox.Text = "" Me.totalBytesTextBox.Text = ""
11
5033
by: Paul Sijben | last post by:
I am stumped by the following problem. I have a large multi-threaded server accepting communications on one UDP port (chosen for its supposed speed). I have been profiling the code and found that the UDP communication is my biggest drain on performance! Communication where the client and the server are on the same machine still takes 300ms or sometimes much more per packet on an Athlon64 3000+ running Linux (Fedora Core 5 x64). I must...
17
6431
by: OlafMeding | last post by:
Below are 2 files that isolate the problem. Note, both programs hang (stop responding) with hyper-threading turned on (a BIOS setting), but work as expected with hyper-threading turned off. Note, the Windows task manager shows 2 CPUs on the Performance tab with hyper-threading is turned on. Both Python 2.3.5 and 2.4.3 (downloaded from python.org) have this problem. The operating system is MS Windows XP Professional.
0
1596
by: kingcrowbar.list | last post by:
Hello Everyone I have been playing a little with pyGTK and threading to come up with simple alert dialog which plays a sound in the background. The need for threading came when in the first version i made, the gui would freeze after clicking the close button until pygame finished playing the sound. In Windows it was acceptable because it could be ignored easily, but in
7
2377
by: Mike P | last post by:
I am trying to write my first program using threading..basically I am moving messages from an Outlook inbox and want to show the user where the process is up to without having to wait until it has finished. I am trying to follow this example : http://www.codeproject.com/cs/miscctrl/progressdialog.asp But although the messages still get moved, the progress window never does anything. Here is my code in full, if anybody who knows...
126
6725
by: Dann Corbit | last post by:
Rather than create a new way of doing things: http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2008/n2497.html why not just pick up ACE into the existing standard: http://www.cse.wustl.edu/~schmidt/ACE.html the same way that the STL (and subsequently BOOST) have been subsumed? Since it already runs on zillions of platforms, they have obviously worked most of the kinks out of the generalized threading and processes idea (along with many...
0
8997
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
8833
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
9568
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
9389
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
9256
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...
1
6801
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
4881
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
2794
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2218
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.