Python在子线程无线循环的过程中,如果直接ctrl+c结束程序的话,虽然程序可以结束,但是会导致子线程资源无法回收,一般情况不会有太大影响,但是使用TCP通信的时候,子线程是占用特定的端口的,在资源没有回收的情况下,再次启动程序就会报端口占用错误可以手动回收资源如下:

# 我的套接字的端口是8899
$ netstat -nap | grep
# 会显示进程号port
$ kill - port

所以参考https://blog.csdn.net/hp_cpp/article/details/83040162博主的方法如下强制结束子线程:

import inspect
import ctypes
from threading import Thread def _async_raise(tid, exctype):
"""raises the exception, performs cleanup if needed"""
tid = ctypes.c_long(tid)
if not inspect.isclass(exctype):
exctype = type(exctype)
res = ctypes.pythonapi.PyThreadState_SetAsyncExc(tid, ctypes.py_object(exctype))
if res == 0:
raise ValueError("invalid thread id")
elif res != 1:
# """if it returns a number greater than one, you're in trouble,
# and you should call it again with exc=NULL to revert the effect"""
ctypes.pythonapi.PyThreadState_SetAsyncExc(tid, None)
raise SystemError("PyThreadState_SetAsyncExc failed") def stop_thread(thread):
_async_raise(thread.ident, SystemExit) def Receive():
while 1:
print(1)
time.sleep(0.1) def Send():
while 1:
print(2)
time.sleep(0.1) if __name__ == "__main__":
t1 = Thread(target=Receive)
t2 = Thread(target=Send)
t1.start()
t2.start()
stop_thread(t1)
stop_thread(t2)

以下是我的测试程序,结合signal方法,主线程一直循环,一旦检测到按下Ctrl+c,就会打印出'You pressed Ctrl+C!'这句话,并且调用上述方法结束两个无限循环的子线程,最后调用exit()方法优雅的结束整个程序

import inspect
import ctypes
import signal
import sys
import time
from threading import Thread def _async_raise(tid, exctype):
"""raises the exception, performs cleanup if needed"""
tid = ctypes.c_long(tid)
if not inspect.isclass(exctype):
exctype = type(exctype)
res = ctypes.pythonapi.PyThreadState_SetAsyncExc(tid, ctypes.py_object(exctype))
if res == 0:
raise ValueError("invalid thread id")
elif res != 1:
# """if it returns a number greater than one, you're in trouble,
# and you should call it again with exc=NULL to revert the effect"""
ctypes.pythonapi.PyThreadState_SetAsyncExc(tid, None)
raise SystemError("PyThreadState_SetAsyncExc failed") def stop_thread(thread):
_async_raise(thread.ident, SystemExit) def signal_handler(signal, frame):
print('You pressed Ctrl+C!')
stop_thread(t1)
stop_thread(t2)
sys.exit() def Receive():
while 1:
print(1)
time.sleep(0.1) def Send():
while 1:
print(2)
time.sleep(0.1) if __name__ == "__main__":
t1 = Thread(target=Receive)
t2 = Thread(target=Send)
t1.start()
t2.start()
print(3)
while True:
signal.signal(signal.SIGINT, signal_handler)
print(4)
time.sleep(0.1)

Pytrhon结束死循环的子线程的更多相关文章

  1. python主线程与子线程的结束顺序

    引用自 主线程退出对子线程的影响--YuanLi 的一段话: 对于程序来说,如果主进程在子进程还未结束时就已经退出,那么Linux内核会将子进程的父进程ID改为1(也就是init进程),当子进程结束后 ...

  2. java 多线程 Thread.join子线程结束父线程再运行;join(long):等待超时毫秒数

    Join的使用 目的:当子线程运行结束后,父线程才能再继续运行 /** * @ClassName ThreadJoinExample * @projectName: object1 * @author ...

  3. C#主线程等待子线程运行结束

    佐左佑右 原文 C#主线程等待子线程运行结束 由于主程序中调用matlab的dll文件进行计算要用较长的时间,主界面会有很长时间的卡顿,造成的用户感受十分不好,因此我想在调用时,将调用放入子线程中,然 ...

  4. Java如何等待子线程执行结束

    工作中往往会遇到异步去执行某段逻辑, 然后先处理其他事情, 处理完后再把那段逻辑的处理结果进行汇总的产景, 这时候就需要使用线程了. 一个线程启动之后, 是异步的去执行需要执行的内容的, 不会影响主线 ...

  5. java主线程结束和子线程结束之间的关系

    (一)Main线程是个非守护线程,不能设置成守护线程. 这是因为,main线程是由java虚拟机在启动的时候创建的.main方法开始执行的时候,主线程已经创建好并在运行了.对于运行中的线程,调用Thr ...

  6. Java_如何等待子线程执行结束

    工作中往往会遇到异步去执行某段逻辑, 然后先处理其他事情, 处理完后再把那段逻辑的处理结果进行汇总的产景, 这时候就需要使用线程了. 一个线程启动之后, 是异步的去执行需要执行的内容的, 不会影响主线 ...

  7. iOS中安全结束 子线程 的方法

    一个典型的结束子线程的方法:   用 isFinished 检测子线程是否被完全kill掉 -(IBAction)btnBack:(id)sender { //释放内存 仅仅remove 并不会触发内 ...

  8. Java Thread.join()详解--父线程等待子线程结束后再结束

    目录(?)[+] 阅读目录 一.使用方式. 二.为什么要用join()方法 三.join方法的作用 join 四.用实例来理解 打印结果: 打印结果: 五.从源码看join()方法   join是Th ...

  9. Java主线程如何等待子线程执行结束(转)

    工作中往往会遇到异步去执行某段逻辑, 然后先处理其他事情, 处理完后再把那段逻辑的处理结果进行汇总的产景, 这时候就需要使用线程了. 一个线程启动之后, 是异步的去执行需要执行的内容的, 不会影响主线 ...

随机推荐

  1. [LeetCode] Minimize Max Distance to Gas Station 最小化去加油站的最大距离

    On a horizontal number line, we have gas stations at positions stations[0], stations[1], ..., statio ...

  2. YARN调试过程中的常见问题

    执行操作: hadoop jar share/hadoop/mapreduce/hadoop-mapreduce-examples-3.1.0.jar wordcount  /user/today/i ...

  3. 熟悉Linux常用命令

    cd命令:切换目录 (1)切换到目录 /usr/localcd / usrcd / local (2)去到目前的上层目录cd .. (3)回到自己的主文件夹cd ls命令:查看文件与目录 (4)查看目 ...

  4. Java常用类库 读书笔记 一

    1.String Buffer 类 String 类所表示的字符串有一个局限就是字符串常量一旦声明则不可改变,只有内存地址的指向可以改变,如果要频繁修改字符串,需要使用String Buffer 类. ...

  5. linux安装zookeeper

    安装环境:Linux:centos6.4Jdk:1.7以上版本 Zookeeper是java开发的可以运行在windows.linux环境.需要先安装jdk.安装步骤:第一步:安装jdk第二步:把zo ...

  6. Xcode工程编译错误之iOS开发之The Xcode build system has crashed. Please close and reopen your workspace

    解决方法: . 删除DerivedData . 参照上面的链接设置:File -> Workspace Settings -> Build System -> Legacy Buil ...

  7. LeetCode 122 Best Time to Buy and Sell Stock II 解题报告

    题目要求 Say you have an array for which the ith element is the price of a given stock on day i. Design ...

  8. 如何让模拟的json数据接口能够正常的在手机上有效果

    1. 确保手机与PC在同一个ip网下 这里我是通过------------360随身WIFI,20块钱淘宝上卖的,外观像U盘一样的,直接插在电脑的USB上就能在PC上创建一个WiFi,手机连接上就可以 ...

  9. 基于binlog恢复工具mysqlbinlog_flashback

    基于binlog恢复工具mysqlbinlog_flashback简介 mysqlbinlog_back.py 是在线读取row格式的mysqld的binlog,然后生成反向的sql语句的工具.一般用 ...

  10. spring boot集成redis实现session共享

    1.pom文件依赖 <!--spring boot 与redis应用基本环境配置 --> <dependency> <groupId>org.springframe ...