run a function in another processor in python
Peter Otten
__peter__ at web.de
Thu Dec 9 09:37:27 EST 2010
Astan Chee wrote:
> Thanks but I'm having trouble with that module too. Currently what I
> have is something like this:
>
> import sys
> import os
> import multiprocessing
>
> import time
>
> def functionTester(num):
> return ((num+2)/(num-2))**2
>
> num_args = [61,62,33,7,12,16,19,35,36,37,38,55,56,57,63]
>
> max_result = 0
>
> start = time.time()
>
> num_processes = multiprocessing.cpu_count()
>
> threads = []
> len_stas = len(num_args)
>
> for list_item in num_args:
> if len(threads) < num_processes:
> p =
> multiprocessing.Process(target=functionTester,args=[list_item])
> p.start() print p, p.is_alive()
> threads.append(p)
> else:
> for thread in threads:
> if not thread.is_alive():
> threads.remove(thread)
>
> print "Result " + str(max_result)
> end = time.time()
> elapsed= end - start
> print "Took", elapsed, "seconds to execute"
>
> But it doesn't give me any return data. It also spawns an infinite
> number of (sub)processes that crashes my machine. What am I doing
> wrong here?
I can't replicate the crash. However, your problem looks like there is a
ready-to-use solution:
http://docs.python.org/library/multiprocessing.html#using-a-pool-of-workers
More information about the Python-list
mailing list