gpt4 book ai didi

python - 如何中断/停止/结束挂起的多线程 python 程序

转载 作者:太空宇宙 更新时间:2023-11-03 11:32:02 28 4
gpt4 key购买 nike

我有一个 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...

然后程序只是挂起或继续打印事件线程。然而,由于退出标志设置为 True,线程的运行方法未被执行。所以我不知道这些线程是如何保持运行或发生了什么。

编辑:我发现了问题。在上面的代码中,线程的 get 方法是阻塞的,因此无法退出。使用带超时的 get 方法就可以了。我有我在下面修改的运行方法的代码

    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))

最佳答案

如果想在进程退出时强制所有线程退出,可以在线程创建前将线程的“daemon”标志设置为True。

http://docs.python.org/2/library/threading.html#threading.Thread.daemon

关于python - 如何中断/停止/结束挂起的多线程 python 程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16681542/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com