473,394 Members | 1,709 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,394 software developers and data experts.

RFC: my iterthreader module

I have this iterthreader module that I've been working on for a while
now. It is similar to itertools.imap, but it calls each function in
its own thread and uses Queues for moving the data around. A better
name for it would probably be ithreadmap, but anyway...

The short explanation of it is if you have a loop like
for item in biglist:
print "The value for %s is %s" % (item, slowfunc(item))
or
for item,val in ((item, slowfunc(item)) for item in biglist):
print "The value for %s is %s" % (item, val)

you can simply rewrite it as

for item,val in iterthreader.Threader(slowfunc, biglist):
print "The value for %s is %s" % (item, val)

and it will hopefully run faster. The usual GIL issues still apply of
course.... You can also subclass it in various ways, but I almost
always just call it in the above manner.

So, can anyone find any obvious problems with it? I've been meaning to
re-post [1] it to the python cookbook, but I'd like to hear what
others think first. I'm not aware of any other module that makes this
particular use of threading this simple.

[1] I _think_ I posted it before, but that may have just been in a
comment

import threading
import Queue

class Threader:
def __init__(self, func=None, data=None, numthreads=2):
if not numthreads 0:
raise AssertionError("numthreads should be greater than 0")

if func:
self.handle_input=func
if data:
self.get_input = lambda : data

self._numthreads=numthreads
self.threads = []
self.run()
def __iter__(self):
return self

def next(self):
still_running, input, output = self.DQ.get()
if not still_running:
raise StopIteration
return input, output

def get_input(self):
raise NotImplementedError, "You must implement get_input as a
function that returns an iterable"

def handle_input(self, input):
raise NotImplementedError, "You must implement handle_input as
a function that returns anything"

def _handle_input(self):
while 1:
work_todo, input = self.Q.get()
if not work_todo:
break
self.DQ.put((True, input, self.handle_input(input)))

def cleanup(self):
"""wait for all threads to stop and tell the main iter to
stop"""
for t in self.threads:
t.join()
self.DQ.put((False,None,None))
def run(self):
self.Q=Queue.Queue()
self.DQ=Queue.Queue()
for x in range(self._numthreads):
t=threading.Thread(target=self._handle_input)
t.start()
self.threads.append(t)

try :
for x in self.get_input():
self.Q.put((True, x))
except NotImplementedError, e:
print e
for x in range(self._numthreads):
self.Q.put((False, None))

threading.Thread(target=self.cleanup).start()
--
- Justin

Jul 18 '06 #1
0 839

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

Similar topics

1
by: praba kar | last post by:
Dear All, In Php we can print RFC 2822 formatted date by date('r') with parameter r. Then it will print the below format date. "Thu, 7 Apr 2005 01:46:36 -0300". I want to print same RFC 2822...
1
by: Randy Charles Morin | last post by:
comments here http://www.kbcafe.com/iblogthere4im/comments.aspx?guid=20030709143822 PSSAPI 0.9 (early draft) Web, July 9 2003, by DeveloperDude. This document describes the Portable and...
47
by: Jeff Relf | last post by:
Hi All, I plan on using the following C++ code to create nodes with unlimited children: // I would like to declare NodeT like this, // but it won't compile because Lnk_T is not defined yet....
0
by: Andy Leszczynski | last post by:
Why email/Encoders.py is missing binary encoding. It should be there according to RFC 1521: encoding := "Content-Transfer-Encoding" ":" mechanism mechanism := "7bit" ; case-insensitive /...
3
by: Dan | last post by:
Hi, I'm trying to call an RFC from a vb web service. I have created the proxy object with no worries but the return table always returns an error even when I get success running the RFC inside...
1
by: Roy Smith | last post by:
Is there any way to access the RFC 3542 defined macros such as ICMP6_FILTER_SETPASSALL() from within the socket module? A dir() on the socket module (Python 2.4.1, built on a solaris box with IPv6...
2
by: Florian Lindner | last post by:
Hello, http://docs.python.org/lib/module-ConfigParser.html writes: "with continuations in the style of RFC 822; " what is meant with these continuations? Thanks, Florian
1
by: fuzzylollipop | last post by:
I want to do email address format validations, without turning to ANTLR or pyparsing, anyone know of a regex that is COMPLIANT with RFC 821. Most of the ones I have found from google searches are...
0
by: js | last post by:
Hi list. Is there any module that is compatible with RFC-3986 or 2396, which is like Perl's URI module(http://search.cpan.org/~gaas/URI-1.35/URI.pm)? I like to normalize lots of URIs I've got...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
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...
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
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...
0
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...

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.