Python Multithreading Problem: Abnormal Program Termination

Wenn du dir nicht sicher bist, in welchem der anderen Foren du die Frage stellen sollst, dann bist du hier im Forum für allgemeine Fragen sicher richtig.
Antworten
professor_rumsdiegeige
User
Beiträge: 5
Registriert: Dienstag 6. Januar 2009, 15:28

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]
Leonidas
Python-Forum Veteran
Beiträge: 16025
Registriert: Freitag 20. Juni 2003, 16:30
Kontaktdaten:

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.
Zuletzt geändert von Leonidas am Mittwoch 7. Januar 2009, 13:40, insgesamt 1-mal geändert.
My god, it's full of CARs! | Leonidasvoice vs (former) Modvoice
professor_rumsdiegeige
User
Beiträge: 5
Registriert: Dienstag 6. Januar 2009, 15:28

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!
Antworten