Alberto
Alberto

Reputation:

How do I manage multiple processes in Python?

I have a simple (i hope) question: my problems started when i wrote a GUI. i cannot refresh the user interface while executing heavy computations.

-if i use threads there is the G.I.L. (not too slow but the gui freezes)

i tryed so many things that my last hope is starting a new process (and here the problem)

first of all: -i never used processes before (it could be a semantic error)

-i don't know the limitations ( and exceptions ) of processes

-i am running with cpython 3.1.2 , on Mac os x v 10.6.8

here is an example (not the real code but the result is the same) of what i need to solve:

from multiprocessing import *
def bob(q):
    print(q)
A=Process(target=bob,args=("something"))
A.start()
A.is_alive()
A.join()

and the output is:

True

it doesn't print "something",so i guess it doesn't run the process,but "A.is_alive()" says it is running and when the interpreter arrives to "A.join()" it waits more or less forever

can someone explain me this?

Upvotes: 1

Views: 1639

Answers (2)

Johan Lundberg
Johan Lundberg

Reputation: 27028

You should give a list of arguments, not just the argument. This does the job for me:

from multiprocessing import *
def bob(q):
    print(q)
A=Process(target=bob,args=["something"])
A.start()
A.is_alive()
A.join()

The following using sleep-sort (http://stackoverflow.com/questions/6474318/what-is-the-time-complexity-of-the-sleep-sort) to sort upper case characters A-Z

somestring="DGAECBF"
from multiprocessing import *
def bob(t):
    import time
    time.sleep(ord(t)-ord("A"))
    print(t)
p=[]
for c in somestring : 
    p.append(Process(target=bob,args=([c])))
    p[-1].start()
for pp in p:
    pp.join()

Upvotes: 1

jfs
jfs

Reputation: 414199

You need to add comma: args=("something",).

Comma creates a tuple otherwise it is just a string in parentheses.

Upvotes: 1

Related Questions