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

调用_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))

python结束多线程_如何中断/停止/结束挂起的多线程python程序相关推荐

  1. python @修饰符_数据结构与算法之8——抽象数据类型与python类

    就算你是特别聪明,也要学习,从头学起!--(俄国)屠格涅夫 本篇文章要说的主要是数据结构与算法和python中关于类(Class)以及异常(Error)的一些基础,虽然很简单,但是必须非常重视.只有在 ...

  2. python装逼_能够让你装逼的10个Python小技巧

    列表推导式 你有一个list: bag = [1, 2, 3, 4, 5] 现在你想让所有元素翻倍,让它看起来是这个样子: [2, 4, 6, 8, 10] 大多初学者,根据之前语言的经验会大概这样来 ...

  3. anaconda的python环境变量_装了anaconda之后如何设置anaconda、python环境变量

    装了anaconda之后如何设置anaconda.python环境变量 1.装了anaconda之后如何设置anaconda环境变量 参考 https://www.cnblogs.com/avivi/ ...

  4. python珠穆朗玛峰问题_学会这6招,让你的Python 嗖嗖嗖的快!

    在后面的程序效率对比上,我们以下面的python程序作为基础对比程序. 01.优化编写的代码 对于 Python程序,大家可以首先将程序的目的实现,然后在这个基础之上,分析程序执行效率低下的部分并实现 ...

  5. python怎么认识_用“讲故事”的方式,带你认识Python编码问题的起源和发展!

    问题起源 我们在学习Python的过程中,可能会经常遇到下方这样的编码问题.有时候我们需要选择gbk,有时候需要选择utf-8.你以为这样就完了吗?我们碰到的还有gb2312,gb18030等各种奇奇 ...

  6. python简单编程语言_功能强大而又简单易学的编程语言Python

    Python是一种面向对象.直译式计算机程序设计语言,也是一种功能强大的通用型语言(维基百科).自从上次写那个批量Blast小程序的时候接触了Python,发现这个玩意儿真是好用,后来还用它弄了个动态 ...

  7. python手把手入门_新手必看:手把手教你入门 Python

    首先,Python是什么?据它的创始人Guido van Rossum而言, "Python是一种高级编程语言,它的核心设计思想是代码可读性和允许程序员用几行代码来表达观点的语法." ...

  8. 虚拟机python建站_搭建本地虚拟服务器linux(CentOS 7)的python虚拟环境(Hyper-V演示)...

    新建虚拟机->安装CentOS7->新建虚拟交换机:内部网络->CentOS7设置->网络适配器:虚拟交换机:新建虚拟交换机->进入CentOS #cd /etc/sys ...

  9. python 字符串操作速度_强者一出,谁与争锋?与Python相比,C+的运行速度究竟有多快?|python|编程语言|字符串|示例|算法...

    对于数据科学家而言,热爱Python的理由数不胜数.但你是否也曾问过这样的问题:Python和C或C++等更专业的低级编程语言究竟有何不同呢?我想这是很多数据科学家或者Python用户曾经问过或者将来 ...

最新文章

  1. Microsoft Speech SDK 编程入门
  2. 字符串-定义和基本使用
  3. ubuntu16 redis5.0以前版本集群部署示例
  4. FastDFS的配置、部署与API使用解读(8)FastDFS多种文件上传接口详解(转)
  5. Type TIMESTAMP(3) of table field ‘onSellTime‘ does not match with the physical type TIMESTAMP(6)
  6. 【bayes】贝叶斯likelihood和model
  7. 津津的储蓄计划(洛谷-P1089)
  8. .net解决Xss攻击
  9. TensorFlow 学习(二)—— tf.Graph、tf.Session() 与 tf.Session().run()
  10. OpenGL基础6:着色器
  11. thinkphp起步
  12. NFS 服务固定端口
  13. 运维人必知必会的Zabbix核心命令
  14. 牛腩新闻发布系统—403.14错误
  15. 清华大学计算机导师排名,清华大学计算机科学与技术系导师简介:周立柱
  16. QDir过滤文件的坑
  17. mysql 模糊匹配比自己短潆字符_根据中文字符串查询拼音声母
  18. iOS12系统这5个隐藏小技巧!你一定要知道,好用到停不下来!
  19. PQ分区魔术师v9.0 中文版
  20. RedisTemplate使用

热门文章

  1. Vijos P1409 纪念品分组【贪心】
  2. Java 技术体系(JDK 与 JRE 的关系)、POJO 与 JavaBeans
  3. 机器学习、深度学习经典课程
  4. 机器学习实践指南(一)—— 总论
  5. Python 技巧(三)—— list 删除一个元素的三种做法
  6. 工具的使用——Photoshop
  7. php db2 页面乱码_DB2代码页设置乱码的处理方法
  8. 七月在线python数据分析_七月在线Python数据分析笔记
  9. python利器-Python利器|给大家推荐几个既好看又好用的-Python编程器
  10. python是什么意思中文、好学吗-爬虫Python入门好学吗?学什么?