如何让多线程python程序响应Ctrl+C键事件?
编辑:代码是这样的:
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()
我试图删除所有线程上的 join() ,但它仍然不起作用。是不是因为每个线程的run()过程里面的lock段?
编辑:上面的代码应该可以工作,但是当当前变量在 5,000-6,000 范围内时它总是中断,并且出现如下错误
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
最佳答案
使除主线程之外的每个线程都成为守护进程(t.daemon = True
在 2.6 或更高版本中,t.setDaemon(True)
在 2.6 或更低版本中,对于每个线程对象 t
在你启动它之前)。这样,当主线程收到 KeyboardInterrupt 时,如果它没有捕捉到它或捕捉到它但决定终止,则整个进程将终止。见 the docs .
编辑:刚刚看到 OP 的代码(不是最初发布的)以及“它不起作用”的说法,看来我必须添加...:
当然,如果您希望您的主线程保持响应(例如控制-C),请不要将其陷入阻塞调用中,例如 join
ing 另一个线程 - 尤其是不完全无用阻塞调用,例如join
ing daemon线程。例如,只需将主线程中的最终循环从当前(完全和破坏性)更改:
for i in range(0, thread_count):
threads[i].join()
到一些更明智的东西,比如:
while threading.active_count() > 0:
time.sleep(0.1)
如果您的 main 没有比让所有线程自行终止或接收 control-C(或其他信号)更好的事情可做。
当然,如果您不想让您的线程突然终止(因为守护线程可能),还有许多其他可用的模式——除非它们也永远陷入无条件阻塞的泥潭调用、死锁等;-)。
关于python - 终止多线程python程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1635080/