Seite 1 von 1

Python Multithreading Problem: Abnormal Program Termination

Verfasst: Mittwoch 7. Januar 2009, 09:27
von professor_rumsdiegeige
I'm having difficulties with multi-threading using Python. For instance, the example script given below either crashes in lines 28 or 29 ("abnormal program termination") or hangs infinitely in line 30, and I do not know why. It simply tries to compute Fibonacci numbers in more than 1 thread (the Fibonacci code itself works and is taken from the Python tutorial).
Can anybody help? Thanks in advance!
Sabine Lorentz

Code: Alles auswählen

from Queue import Queue
from threading import Thread
num_worker_threads = 2

def do_work(c):
    a, b = 0, 1
    while b < c:
        #print b
        a, b = b, a+b
    print b
    return b;

def worker():
    while True:
        item = q.get()
        do_work(item)
        q.task_done()
    return;

q = Queue()
for i in range(num_worker_threads):
     t = Thread(target=worker)
     t.setDaemon(True)
     t.start()

print "Start."
#q.put(10)
q.put(301)
q.put(25)
q.join(5)       # block until all tasks are do
#o = do_work(25);
#print o
#o = do_work(301);
#print o
print "End."
[/quote]

Verfasst: Mittwoch 7. Januar 2009, 11:09
von Leonidas
Hallo professor_rumsdiegeige, willkommen im Forum,

Funktioniert hier ohne irgendwelche Crashes wenn man das ``join`` korrigiert.

Code: Alles auswählen

from Queue import Queue
from threading import Thread
num_worker_threads = 2

def do_work(c):
    a, b = 0, 1
    while b < c:
        #print b
        a, b = b, a+b
    print b
    return b

def worker():
    while True:
        item = q.get()
        do_work(item)
        q.task_done()

q = Queue()
for i in range(num_worker_threads):
     t = Thread(target=worker)
     t.setDaemon(True)
     t.start()

print "Start."
q.put(301)
q.put(25)
q.join()
print "End."
Ausgabe:

Code: Alles auswählen

Start.
377
34
End.

Verfasst: Mittwoch 7. Januar 2009, 13:24
von professor_rumsdiegeige
Danke, jetzt stürzt es nicht mehr ab. Aber manchmal, sagen wir bei jeder 10. Programmausführung, bleibt es einfach hängen, und man muss den Prozess abschießen. Fehlen denn noch irgendwelche Synchronisierungsmaßnahmen, oder darf z.B. "print" nicht multi-threaded benutzt werden?
Danke nochmals!