473,606 Members | 3,113 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Threading Pool Event()

Hi all

I just cannot seem to find any documentation that shows an example of using
the factory method Event() in threads. I have a thread pool and if there are
no jobs in a Queue I want them to wait for something to be inserted. When a
job is inserted I want to send an Event, the first thread that picks it up
runs with the job the rest wait for another insert Event.

I have been looking at some C, c++ implementations and some use a continious
loop within a thread that polls the queue then if one is found pops it from
the queue and runs with it.

Problem when threads are dormant is it not better having the main thread
(i.e process) sending a signal rather than 10 threads polling surely this is
cpu intensive ??

any helps or references on Event() is much appreciated

many thanks

Graeme
Jul 18 '05 #1
8 4201
In article <0t************ ****@nnrp1.ozem ail.com.au>,
Graeme Matthew <gs*******@ozem ail.com.au> wrote:

I just cannot seem to find any documentation that shows an example of
using the factory method Event() in threads. I have a thread pool and
if there are no jobs in a Queue I want them to wait for something to
be inserted. When a job is inserted I want to send an Event, the first
thread that picks it up runs with the job the rest wait for another
insert Event.


Given that you're already using a Queue, there is no, repeat NO, reason
for using an Event. Just have your threads block on the Queue.
--
Aahz (aa**@pythoncra ft.com) <*> http://www.pythoncraft.com/

A: No.
Q: Is top-posting okay?
Jul 18 '05 #2
Aahz

Thanks, ive actually been using your OSCON slides which have helped a lot.
So it technically correct that all worker threads in a thread pool are
either doing some work or polling the queue to find out if there is a job
to process ?

eg: (pseudocodish :-))

def run(self):

while 1:

self.lock.acqui re()

if QueueManager.Ha sJob:
job = QueueManager.Ge tFreeJob()
__processJob(jo b)

self.lock.relea se()

def __processJob(se lf):

blah blah blah .....
many thanks ......
"Aahz" <aa**@pythoncra ft.com> wrote in message
news:bf******** **@panix1.panix .com...
In article <0t************ ****@nnrp1.ozem ail.com.au>,
Graeme Matthew <gs*******@ozem ail.com.au> wrote:

I just cannot seem to find any documentation that shows an example of
using the factory method Event() in threads. I have a thread pool and
if there are no jobs in a Queue I want them to wait for something to
be inserted. When a job is inserted I want to send an Event, the first
thread that picks it up runs with the job the rest wait for another
insert Event.
Given that you're already using a Queue, there is no, repeat NO, reason
for using an Event. Just have your threads block on the Queue.
--
Aahz (aa**@pythoncra ft.com) <*>

http://www.pythoncraft.com/
A: No.
Q: Is top-posting okay?

Jul 18 '05 #3
In article <ND************ *****@nnrp1.oze mail.com.au>,
Graeme Matthew <gs*******@ozem ail.com.au> wrote:

Thanks, ive actually been using your OSCON slides which have helped a
lot. So it technically correct that all worker threads in a thread
pool are either doing some work or polling the queue to find out if
there is a job to process ?
The whole point is that it *doesn't* poll. It blocks on a lock internal
to the Queue object. That makes it extremely efficient.
eg: (pseudocodish :-))

def run(self):

while 1:

self.lock.acqui re()

if QueueManager.Ha sJob:
job = QueueManager.Ge tFreeJob()
__processJob(jo b)

self.lock.relea se()

def __processJob(se lf):

blah blah blah .....


Nope, it's even simpler than that:

def run(self):
done = False
while not done:
job = q.get()
if job.done:
done = True
else:
__processJob(jo b)

The Queue handles all the locks for you.
--
Aahz (aa**@pythoncra ft.com) <*> http://www.pythoncraft.com/

A: No.
Q: Is top-posting okay?
Jul 18 '05 #4
On Fri, 2003-07-18 at 14:28, Graeme Matthew wrote:
Aahz

Thanks, ive actually been using your OSCON slides which have helped a lot.
So it technically correct that all worker threads in a thread pool are
either doing some work or polling the queue to find out if there is a job
to process ?
They don't poll the queue, they block waiting on it until something is
available.
eg: (pseudocodish :-))

def run(self):

while 1:

self.lock.acqui re()

if QueueManager.Ha sJob:
job = QueueManager.Ge tFreeJob()
__processJob(jo b)

self.lock.relea se()

def __processJob(se lf):

blah blah blah .....


More like:

def run():
while 1:
job = queue.get() # this blocks until something is queue.put()
_processjob(job )
Acquiring the locks isn't necessary and ill-advised. The Queue itself
can be thought of as a type of locking mechanism, so you raise the
possibility of a deadlock condition by nesting locks (for instance if
you also put locks around the queue.put()).

Regards,

--
Cliff Wells, Software Engineer
Logiplex Corporation (www.logiplex.net)
(503) 978-6726 (800) 735-0555
Jul 18 '05 #5
ok still a bit confused sorry .... first attempt at a thread pool

Am I correct in saying that each thread runs in a continious loop

each thread calls queue.get. The get method will block and not return
anything until an item is placed into it. When an item is placed into it,
one of the threads will get assinged a job i.e the first one that happens to
be in use during the cycle ?

The job is returned to the thread, it runs with the job and does all the
processing then returns and calls queue.get again and waits for a job to
become available ?

When placing a job via Queue.put() one must acquire a lock place it and then
release it

Am i aslo correct in saying that queue is actually doing the blocking and
controls which thread gets the job ?

Lastly, sorry for all the questions, surely the CPU usage is the same when
the queue is waiting for jobs and when the threads are polling as theyre all
in one process anyway

thanks very much for your help

Graeme
Am i getting this or am i way off :-)
"Graeme Matthew" <gs*******@ozem ail.com.au> wrote in message
news:ND******** *********@nnrp1 .ozemail.com.au ...
Aahz

Thanks, ive actually been using your OSCON slides which have helped a lot.
So it technically correct that all worker threads in a thread pool are
either doing some work or polling the queue to find out if there is a job
to process ?

eg: (pseudocodish :-))

def run(self):

while 1:

self.lock.acqui re()

if QueueManager.Ha sJob:
job = QueueManager.Ge tFreeJob()
__processJob(jo b)

self.lock.relea se()

def __processJob(se lf):

blah blah blah .....
many thanks ......
"Aahz" <aa**@pythoncra ft.com> wrote in message
news:bf******** **@panix1.panix .com...
In article <0t************ ****@nnrp1.ozem ail.com.au>,
Graeme Matthew <gs*******@ozem ail.com.au> wrote:

I just cannot seem to find any documentation that shows an example of
using the factory method Event() in threads. I have a thread pool and
if there are no jobs in a Queue I want them to wait for something to
be inserted. When a job is inserted I want to send an Event, the first
thread that picks it up runs with the job the rest wait for another
insert Event.


Given that you're already using a Queue, there is no, repeat NO, reason
for using an Event. Just have your threads block on the Queue.
--
Aahz (aa**@pythoncra ft.com) <*>

http://www.pythoncraft.com/

A: No.
Q: Is top-posting okay?


Jul 18 '05 #6
On Fri, 2003-07-18 at 18:29, Graeme Matthew wrote:
ok still a bit confused sorry .... first attempt at a thread pool

Am I correct in saying that each thread runs in a continious loop
Yes.
each thread calls queue.get. The get method will block and not return
anything until an item is placed into it. When an item is placed into
it, one of the threads will get assinged a job i.e the first one that
happens to be in use during the cycle ?
I think you have the idea, but I'm not sure (your terminology escapes me
a bit toward the end). What happens is each thread blocks waiting for
something to be placed on the queue. When something is put on the
queue, one of the available threads (i.e. one that is blocking on
queue.get() rather than processing a job). Only a single thread will be
woken for each item that is put on the queue. It isn't knowable which
thread that will be.
The job is returned to the thread, it runs with the job and does all
the processing then returns and calls queue.get again and waits for a
job to become available ?
Yes.
When placing a job via Queue.put() one must acquire a lock place it
and then release it
No. The locking semantics are internal to the Queue object. Do not
concern yourself with it. It simply works. Do not attempt to put locks
around it.
Am i aslo correct in saying that queue is actually doing the blocking
and controls which thread gets the job ?
In a sense (that is, for practical purposes). How it is done internally
by the interpreter isn't important.
Lastly, sorry for all the questions, surely the CPU usage is the same
when the queue is waiting for jobs and when the threads are polling as
theyre all in one process anyway
The threads are asleep while waiting. They don't consume any CPU. The
queue doesn't "wait" for jobs (that is, it doesn't loop, poll or
otherwise consume any CPU time), when you call queue.put() it is a
method call on an object, not a thread.
Am i getting this or am i way off :-)


Just a little way off ;)

Regards,

Cliff

--
My only regret is that I ever was born
-Swans
Jul 18 '05 #7
Graeme Matthew wrote:

ok so code like this is perfectly safe

def run(self):

while 1:

job = queue.get()

__processjob()


It's almost like you aren't even seeing Aahz' replies. ;-)

The above is certainly safe, but can't be terminated easily.
Just use the loop Aahz showed, which is the above plus the
ability to terminate.

-Peter
Jul 18 '05 #8
Graeme Matthew wrote:
here is my code, please criticise it to death i wont take offence
[snip]
#ON A MULTIPLE CPU MACHINE 2 SEPERATE SERVERS SHOULD BE RUN
#THE INCOMING REQUEST WILL NEED TO BE SWITCHED BETWEEN SERVERS
#THIS IS DUE TO THE GLOBAL INTERPRETER LOCK (GIL) IN PYTHON


If my understanding of your intentions is correct, then I think you're
expecting that multiple python threads within the same interpreter
will migrate to multiple processors, and thus execute in parallel,
i.e. simultaneously on multiple processors.

However, the GIL prevents precisely that: if you have one python
thread running on one processor, it will lock the GIL, thus causing
all other python threads on other processors to be suspended until the
GIL is free again.

One way to achieve true concurrency across multiple processors is
to release the GIL when you are processing, which you cannot do from
within python code. You have to write a C language extension to do the
work, that releases the GIL before doing its job, and reacquires it
again when finished.

If you really want true concurrency, and still want to write in pure
python, then one way to do it is run multiple python interpreters in
separate OS processes, which are bound to different processors. Which
means that

1. You can no longer use Queue.Queue objects to communicate between
servers, since your servers no longer share an address space.

2. You have to use some alternate comms mechanism between the two
servers, such as shared memory, named pipes or something like Pyro.

3. You can no longer pass the socket object across wrapped in a "job"
object, since the file descriptor tables of the two server processes
will be different.

Lastly, I have a question of my own: I've read statements along the
lines of "having the GIL in python provides certain guarantees that
make certain things possible". I can't remember specifics. I'd be most
grateful if someone could point me to reading material (apart from the
source, Luke :-) which describes what these guarantees are, and what
they make possible.

TIA,

--
alan kennedy
-----------------------------------------------------
check http headers here: http://xhaus.com/headers
email alan: http://xhaus.com/mailto/alan
Jul 18 '05 #9

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

Similar topics

8
8376
by: Ivan Nestlerode | last post by:
Hello comp.lang.python, I am attempting to write a threaded program right now in Python (version 2.3 on Debian unstable) and the current behavior of KeyboardInterrupt is causing me grief. From the documentation of the thread module in Python 2.3.3: "Threads interact strangely with interrupts: the KeyboardInterrupt exception will be received by an arbitrary thread. (When the signal module is available, interrupts always go to the main...
1
1699
by: Simon Roses Femerling | last post by:
Hi all :) Anyone got a nice & simple threading pool example? I'm working on a wxpython app that runs plugins, so I want the plugins to run in a threading pool so the GUI is not blocked. Sincerely, Simon Roses Femerling
3
539
by: Suhail Salman | last post by:
Dear All, i got the following error message in an applications that opens 13 threads and all of them calling a stored procedure which retreieves data from SQLServer and fills them to a table the error appears at the following statment sqlda.Fill(dtMessages); During an infinit loopp
6
2853
by: Dan | last post by:
I've created a pocketpc app which has a startup form containing a listview. The form creates an object which in turn creates a System.Threading.Timer. It keeps track of the Timer state using a TimerState object similar to the example in the System.Threading.Timer documentation. The method which handles the timer events, among other things, periodically calls a method in this TimerState object which raises an event to the startup form,...
0
982
by: BenLeino | last post by:
Hi out there, I have a little problem with threading an event receiving. I have a custom Class (DLL) that raises Events. When I run the Instance without threading it works fine. When I do threading no Events are received. Code:
2
1415
by: hecklar | last post by:
This is my first time posting here, so i apologize if i'm posting in the wrong subgroup or whatever, but here goes... I’m having a problem with threading and events (permissions?) in a VB.net Windows application (background service). I’m trying to write an application that processes files, launching a new thread for each file that is dropped into a certain folder. Now, the application works like a charm on my Win2000 machine, but...
10
4564
by: jt | last post by:
The program works like this: There is a form with a button. When the form is loaded, a separate thread is started which is retreiving/updating data in the database every x seconds. When clicked on the button, data is retrieved from the database. This looks to work fine. However, sometimes after clicking on the butten to retrieve the data i got an error message (on the separate thread): "The connection is already Open"
0
1663
by: roni schuetz | last post by:
since a few day's i'm running around the problem that I stocked with a change i need to do. hopefully somebody here can give me a tipp which will be usefull to solve my problem. I'm using a thread-pool within my WebSite which done some requests to several interfaces the readed data will be added to the cache. This operations consumes much CPU and I want to have this outside my website so i decided to change the flow. It should looks...
9
2847
by: cmwb2000 | last post by:
I am trying to build a peice of software to survey how a user interacts with a pc. I need to record keystroke latencies and durations etc. I have got the event handler working and I was wanting to create a seperate class for each parameter such as keystroke latency etc. I got it working on the main thread but when I ran latency and duration together they interfiered with each other. Im guessing I am going to have to run them on sperate...
0
8036
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
7978
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
8461
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...
1
8126
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 most users, this new feature is actually very convenient. If you want to control the update process,...
0
6796
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...
0
5470
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
3948
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...
1
1572
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
1313
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.