473,397 Members | 1,985 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,397 software developers and data experts.

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 2477
"Perecli Manole" <Pe*****@dslextreme.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(100) inside the loop?
--
Armin

Nov 20 '05 #2
Perecli,
In addition to Armin's suggestion. I normally use a
System.Threading.AutoResetEvent 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*****@dslextreme.com> wrote in message
news:Ov**************@tk2msftngp13.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.ThreadState = ThreadState.WaitSleepJoin Then
oThread.Interrupt 'Hey!! Sleepy Head! - I've a job for you.
End If
End Sub

Sub FinishTheJobAndGoHome(..)
While oThread.ThreadState <> ThreadState.WaitSleepJoin
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 ThreadInterruptedException
'Yawn, .. streeeetch,... better get back to work.
End Try
Loop
Catch e As ThreadAbortException
'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.SyncRoot
m_objCmdQueue.Enqueue(objCommand)
End SyncLock
End If
End Sub

Private Sub BackgroundThread()
Dim objCommand As ICmdExecute

While True
'dequeue all available commands
Do
SyncLock m_objCmdQueue.SyncRoot
If m_objCmdQueue.Count > 0 Then
objCommand = m_objCmdQueue.Dequeue()
End If
End SyncLock

If objCommand Is Nothing Then
Exit Do
Else
objCommand.Execute()
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********@email.msn.com> wrote in message
news:eL**************@TK2MSFTNGP10.phx.gbl...
Perecli,
In addition to Armin's suggestion. I normally use a
System.Threading.AutoResetEvent 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*****@dslextreme.com> wrote in message
news:Ov**************@tk2msftngp13.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
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...
2
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...
77
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...
6
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...
2
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...
11
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...
17
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. ...
0
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...
7
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...
126
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:...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
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,...
0
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...
0
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,...
0
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...
0
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...

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.