Velocity Reviews - Computer Hardware Reviews

Velocity Reviews > Newsgroups > Programming > Python > Multiprocessing.Queue - I want to end.

Reply
Thread Tools

Multiprocessing.Queue - I want to end.

 
 
Luis Zarrabeitia
Guest
Posts: n/a
 
      04-30-2009

Hi. I'm building a script that closely follows a producer-consumer model. In
this case, the producer is disk-bound and the consumer is cpu-bound, so I'm
using the multiprocessing module (python2.5 with the multiprocessing backport
from google.code) to speed up the processing (two consumers, one per core,
and one producer). The consumers are two multiprocessing.Process instances,
the producer is the main script, and the data is sent using a
multiprocessing.Queue instance (with bounded capacity).

The problem: when there is no more data to process, how can I signal the
consumers to consume until the queue is empty and then stop consuming? I need
them to do some clean-up work after they finish (and then I need the main
script to summarize the results)

Currently, the script looks like this:

===
from multiprocessing import Queue, Process

def consumer(filename, queue):
outfile = open(filename,'w')
for data in iter(queue.get, None):
process_data(data, outfile) # stores the result in the outfile
outfile.close()
cleanup_consumer(filename)

if __name__ == "__main__":
queue = Queue(100)
p1 = Process(target=consumer, args=("file1.txt", queue))
p2 = Process(target=consumer, args=("file1.txt", queue))
p1.start(); p2.start()
for item in read_from_disk(): # this is the disk-bound operation
queue.put(item)
queue.put(None); queue.put(None)
p1.join() # Wait until both consumers finish their work
p2.join()
# Tried to put this one before... but then the 'get' raises
# an exception, even if there are still items to consume.
queue.close()
summarize() # very fast, no need to parallelize this.
===

As you can see, I'm sending one 'None' per consumer, and hoping that no
consumer will read more than one None. While this particular implementation
ensures that, it is very fragile. Is there any way to signal the consumers?
(or better yet, the queue itself, as it is shared by all consumers?)
Should "close" work for this? (raise the exception when the queue is
exhausted, not when it is closed by the producer).

--
Luis Zarrabeitia (aka Kyrie)
Fac. de Matemática y Computación, UH.
http://profesores.matcom.uh.cu/~kyrie
 
Reply With Quote
 
 
 
 
Aaron Brady
Guest
Posts: n/a
 
      05-01-2009
On Apr 30, 3:49*pm, Luis Zarrabeitia <ky...@uh.cu> wrote:
> Hi. I'm building a script that closely follows a producer-consumer model. In
> this case, the producer is disk-bound and the consumer is cpu-bound, so I'm
> using the multiprocessing module (python2.5 with the multiprocessing backport
> from google.code) to speed up the processing (two consumers, one per core,
> and one producer). The consumers are two multiprocessing.Process instances,
> the producer is the main script, and the data is sent using a
> multiprocessing.Queue instance (with bounded capacity).
>
> The problem: when there is no more data to process, how can I signal the
> consumers to consume until the queue is empty and then stop consuming? I need
> them to do some clean-up work after they finish (and then I need the main
> script to summarize the results)

snip
> * * for data in iter(queue.get, None):
> * * * * process_data(data, outfile) # stores the result in the outfile

snip
> * * queue.put(None); queue.put(None)

snip
> As you can see, I'm sending one 'None' per consumer, and hoping that no
> consumer will read more than one None. While this particular implementation
> ensures that, it is very fragile. Is there any way to signal the consumers?
> (or better yet, the queue itself, as it is shared by all consumers?)
> Should "close" work for this? (raise the exception when the queue is
> exhausted, not when it is closed by the producer).


You may have to write the consumer loop by hand, rather than using
'for'. In the same-process case, you can do this.

producer:
sentinel= object( )

consumer:
while True:
item= queue.get( )
if item is sentinel:
break
etc.

Then, each consumer is guaranteed to consume no more than one
sentinel, and thus producing one sentinel per consumer will halt them
all.

However, with multiple processes, the comparison to 'sentinel' will
fail, since each subprocess gets a copy, not the original, of the
sentinel. A sample program which sent the same object multiple times
produced this output:

<object object at 0x00B8A388>
<object object at 0x00B8A3A0>

Theoretically, you could send a shared object, which would satisfy the
identity test in the subprocess. That failed with this exception:

File "c:\programs\python30\lib\multiprocessing\queues.p y", line 51,
in __getstate__
assert_spawning(self)
....
RuntimeError: Queue objects should only be shared between processes th
rough inheritance

As a result, your options are more complicated. I think the best
option is to send a tuple with the data. Instead of sending 'item',
send '( True, item )'. Then when the producer is finished, send
'( False, <any> )'. The consumer will break when it encounters a
'False' first value.

An alternative is to spawn a watchman thread in each subprocess, which
merely blocks for a shared Event object, then sets a per-process
variable, then adds a dummy object to the queue. The dummy is
guaranteed to be added after the last of the data. Each process is
guaranteed to consume no more than one dummy, so they will all wake
up.

If you don't like those, you could just use a time-out, which checks
the contents of a shared variable, like a one-element array, then
checks the queue to be empty. If the shared variable is True, and the
queue is empty, there is no more data.

I'm curious how these work and what you decide.
 
Reply With Quote
 
 
 
 
Luis Alberto Zarrabeitia Gomez
Guest
Posts: n/a
 
      05-04-2009

Quoting Dennis Lee Bieber <>:

> I'm not familiar with the multiprocessing module and its queues but,
> presuming it behaves similar to the threading module AND that you have
> design control over the consumers (as you did in the sample) make a
> minor change.
>
> queue.put(None) ONCE in the producer
>
> Then, in the consumer, after it sees the None and begins shutdown
> processing, have the consumer ALSO do
>
> queue.put(None)
>


Thank you. I went with this idea, only that instead of modifying the consumer, I
modified the queue itself... Well, Cameron Simpson did . It's working nicely now.

--
Luis Zarrabeitia
Facultad de Matemática y Computación, UH
http://profesores.matcom.uh.cu/~kyrie

--
Participe en Universidad 2010, del 8 al 12 de febrero de 2010
La Habana, Cuba
http://www.universidad2010.cu

 
Reply With Quote
 
rylesny@gmail.com
Guest
Posts: n/a
 
      05-04-2009
> You may have to write the consumer loop by hand, rather than using
> 'for'. *In the same-process case, you can do this.
>
> producer:
> sentinel= object( )
>
> consumer:
> while True:
> * item= queue.get( )
> * if item is sentinel:
> * * break
> * etc.
>
> Then, each consumer is guaranteed to consume no more than one
> sentinel, and thus producing one sentinel per consumer will halt them
> all.
>
> However, with multiple processes, the comparison to 'sentinel' will
> fail, since each subprocess gets a copy, not the original, of the
> sentinel.


Rather than use object() you can create a type whose instances are
equal.

class Stopper(object):
def __eq__(self, other):
return type(other) == type(self)

producer's stop():
queue.put(Stopper())

consumers main loop:
for item in iter(queue.get, Stopper()):
...
 
Reply With Quote
 
 
 
Reply

Thread Tools

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are Off


Similar Threads
Thread Thread Starter Forum Replies Last Post
I want to output all of my STDOUT to a single line....dont want to scroll seancsnyder@gmail.com Perl Misc 4 09-13-2006 04:32 PM
I want to create a link "e-mail this page to a friend" on clicking this link i want to send the URL of that current page to a friend pavi Javascript 0 01-13-2006 12:10 PM
Do want this HDD given away? unholy The Lounge 36 11-16-2005 05:41 PM
Hi I have one web application and i want to get the number of users who are currently accessing the application. Also I want to get the user details of each user, which is stored in a database. How can I do this? Pls help. Getting No: and anu Java 11 05-12-2005 03:25 PM
Have a new laptop, want to add it to my home network!?!? =?Utf-8?B?U3R1?= Wireless Networking 4 07-28-2004 03:51 AM



Advertisments