如何中断/停止/结束挂起的多线程python程序
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了如何中断/停止/结束挂起的多线程python程序,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含3841字,纯文字阅读大概需要6分钟。
内容图文
![如何中断/停止/结束挂起的多线程python程序](/upload/InfoBanner/zyjiaocheng/778/725194e0607d454890235c67e0b229df.jpg)
我有一个python程序,实现这样的线程:
class Mythread(threading.Thread):
def __init__(self, name, q):
threading.Thread.__init__(self)
self.name = name
self.q = q
def run(self):
print "Starting %s..." % (self.name)
while True:
## Get data from queue
data = self.q.get()
## do_some_processing with data ###
process_data(data)
## Mark Queue item as done
self.q.task_done()
print "Exiting %s..." % (self.name)
def call_threaded_program():
##Setup the threads. Define threads,queue,locks
threads = []
q = Queue.Queue()
thread_count = n #some number
data_list = [] #some data list containing data
##Create Threads
for thread_id in range(1, thread_count+1):
thread_name = "Thread-" + str(thread_id)
thread = Mythread(thread_name,q)
thread.daemon = True
thread.start()
##Fill data in Queue
for data_item in data_list:
q.put(data_item)
try:
##Wait for queue to be exhausted and then exit main program
q.join()
except (KeyboardInterrupt, SystemExit) as e:
print "Interrupt Issued. Exiting Program with error state: %s"%(str(e))
exit(1)
call_threaded_program()是从另一个程序调用的.
我有正常情况下的代码.但是,如果其中一个线程发生错误/异常,则程序被卡住(因为队列连接无限阻塞).我能够退出该程序的唯一方法是关闭终端本身.
线程挽救时终止此程序的最佳方法是什么?这样做是否干净(实际上我会采取任何方式)?我知道这个问题已被多次询问,但我仍然无法找到令人信服的答案.我真的很感激任何帮助.
编辑:
我尝试删除队列中的连接并使用Is there any way to kill a Thread in Python?中建议的全局退出标志
然而,现在行为是如此奇怪,我无法理解发生了什么.
import threading
import Queue
import time
exit_flag = False
class Mythread (threading.Thread):
def __init__(self,name,q):
threading.Thread.__init__(self)
self.name = name
self.q = q
def run(self):
try:
# Start Thread
print "Starting %s...."%(self.name)
# Do Some Processing
while not exit_flag:
data = self.q.get()
print "%s processing %s"%(self.name,str(data))
self.q.task_done()
# Exit thread
print "Exiting %s..."%(self.name)
except Exception as e:
print "Exiting %s due to Error: %s"%(self.name,str(e))
def main():
global exit_flag
##Setup the threads. Define threads,queue,locks
threads = []
q = Queue.Queue()
thread_count = 20
data_list = range(1,50)
##Create Threads
for thread_id in range(1,thread_count+1):
thread_name = "Thread-" + str(thread_id)
thread = Mythread(thread_name,q)
thread.daemon = True
threads.append(thread)
thread.start()
##Fill data in Queue
for data_item in data_list:
q.put(data_item)
try:
##Wait for queue to be exhausted and then exit main program
while not q.empty():
pass
# Stop the threads
exit_flag = True
# Wait for threads to finish
print "Waiting for threads to finish..."
while threading.activeCount() > 1:
print "Active Threads:",threading.activeCount()
time.sleep(1)
pass
print "Finished Successfully"
except (KeyboardInterrupt, SystemExit) as e:
print "Interrupt Issued. Exiting Program with error state: %s"%(str(e))
if __name__ == '__main__':
main()
该程序的输出如下:
#Threads get started correctly
#The output also is getting processed but then towards the end, All i see are
Active Threads: 16
Active Threads: 16
Active Threads: 16...
然后程序挂起或继续打印活动线程.但是,由于exit标志设置为True,因此不会执行线程的run方法.所以我不知道这些线程如何保持或正在发生什么.
编辑:
我发现了这个问题.在上面的代码中,线程的get方法是阻塞的,因此无法退出.使用带超时的get方法代替了这个技巧.我有下面修改的run方法的代码
def run(self):
try:
#Start Thread
printing "Starting %s..."%(self.name)
#Do Some processing
while not exit_flag:
try:
data = self.q.get(True,self.timeout)
print "%s processing %s"%(self.name,str(data))
self.q.task_done()
except:
print "Queue Empty or Timeout Occurred. Try Again for %s"%(self.name)
# Exit thread
print "Exiting %s..."%(self.name)
except Exception as e:
print "Exiting %s due to Error: %s"%(self.name,str(e))
解决方法:
如果要在进程退出时强制退出所有线程,可以在创建线程之前将线程的“守护程序”标志设置为True.
http://docs.python.org/2/library/threading.html#threading.Thread.daemon
内容总结
以上是互联网集市为您收集整理的如何中断/停止/结束挂起的多线程python程序全部内容,希望文章能够帮你解决如何中断/停止/结束挂起的多线程python程序所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。