Wie kann ein Python-Programm mit mehreren Threads auf Strg + C-Schlüsselereignis reagieren?
Bearbeiten: Der Code ist wie folgt:
import threading
current = 0
class MyThread(threading.Thread):
def __init__(self, total):
threading.Thread.__init__(self)
self.total = total
def stop(self):
self._Thread__stop()
def run(self):
global current
while current<self.total:
lock = threading.Lock()
lock.acquire()
current+=1
lock.release()
print current
if __name__=='__main__':
threads = []
thread_count = 10
total = 10000
for i in range(0, thread_count):
t = MyThread(total)
t.setDaemon(True)
threads.append(t)
for i in range(0, thread_count):
threads[i].start()
Ich habe versucht, join () für alle Threads zu entfernen, aber es funktioniert immer noch nicht. Liegt es daran, dass das Sperrsegment in der run () -Prozedur jedes Threads enthalten ist?
Bearbeiten: Der obige Code soll funktionieren, wird jedoch immer unterbrochen, wenn die aktuelle Variable im Bereich von 5.000 bis 6.000 liegt und die folgenden Fehler auftreten
Exception in thread Thread-4 (most likely raised during interpreter shutdown):
Traceback (most recent call last):
File "/usr/lib/python2.5/threading.py", line 486, in __bootstrap_inner
File "test.py", line 20, in run
<type 'exceptions.TypeError'>: unsupported operand type(s) for +=: 'NoneType' and 'int'
Exception in thread Thread-2 (most likely raised during interpreter shutdown):
Traceback (most recent call last):
File "/usr/lib/python2.5/threading.py", line 486, in __bootstrap_inner
File "test.py", line 22, in run
concurrent.futuresModul . Ich versuche immer noch herauszufinden, ob oder wie eine der Lösungen hier vonthreadingzu übersetzt wirdconcurrent.futures.