Python-主线程控制子线程-4

news2024/9/25 21:26:14

需求:在Python-主线程控制子线程-3的基础上,新增使用UDP接收指令功能,代替从键盘输入指令

# 修改后的程序,主线程可以获取子线程的结果
import threading
import time
import queue
import traceback

from loguru import logger
import socket


class WorkerThread(threading.Thread):
    def __init__(self, result_queue):
        super().__init__()
        self.stop_event = threading.Event()
        self.result_queue = result_queue

    static_variable = 0

    def run(self):
        thread_id = threading.get_ident()
        print(f"Worker thread {thread_id} has started.")
        while not self.stop_event.is_set():
            print(f"Worker thread {thread_id} is running.")
            result = self.do_work()
            self.result_queue.put(result)
            time.sleep(1)
        print(f"Worker thread {thread_id} has stopped.")

    def increment_static_variable(cls):
        cls.static_variable += 1

    def do_work(self):  # Simulate some work
        # self.increment_static_variable()
        self.static_variable += 1
        return self.static_variable

    def stop(self):
        self.stop_event.set()
        self.join()  # 等待子线程结束


class KeyListener:
    def __init__(self, result_queue_listener):
        self.server_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        self.address = ("127.0.0.1", 12580)
        self.server_socket.bind(self.address)
        self.stop_event = threading.Event()
        self.result_queue_listener = result_queue_listener

    def udp_recv(self):
        while not self.stop_event.is_set():
            try:
                receive_dat, client_address = self.server_socket.recvfrom(1024)
                command = receive_dat.decode()
                print(command)
                self.result_queue_listener.put(command)
            except socket.error:
                # This will be triggered when the socket is closed
                pass

    def start(self):
        keyboard_thread = threading.Thread(target=self.udp_recv)  # 创建键盘输入监听线程
        keyboard_thread.start()
        logger.info(f"Keyboard monitor thread {keyboard_thread.ident} has started~")

    def stop(self):
        self.stop_event.set()
        self.server_socket.close()


def end_child_thread():
    try:
        if worker_thread.is_alive():
            worker_thread.stop()
            logger.info(f"Stopping worker thread {worker_thread.ident}...")
            if worker_thread.is_alive():
                logger.info(f"Worker thread {worker_thread.ident} is still active")
        else:
            logger.info(f"Worker thread {worker_thread.ident} doesn't exist ..")
    except Exception as e:
        logger.info("中止线程失败:" + e)


if __name__ == '__main__':
    result_queue = queue.Queue()
    result_queue_listener = queue.Queue()
    main_thread_id = threading.main_thread().ident
    logger.info(f"Main thread {main_thread_id} has started~")

    worker_thread = WorkerThread(result_queue)
    worker_thread.start()
    logger.info(f"worker thread {worker_thread.ident} has started~")

    key_listener = KeyListener(result_queue_listener)
    key_listener.start()

    exit_program = False

    try:
        while not exit_program:
            if not result_queue_listener.empty():
                command = result_queue_listener.get()
                if command == '0':
                    logger.info(f"工作线程状态{worker_thread}")
                    end_child_thread()
                    logger.info(f"工作线程状态{worker_thread}")
                elif command == '1':
                    try:
                        if worker_thread.is_alive():
                            pass
                        else:
                            worker_thread = WorkerThread(result_queue)
                            worker_thread.start()
                            logger.info(f"Started new worker thread {worker_thread.ident}")
                    except Exception as e:
                        logger.info("新建工作线程失败:" + e)
                elif command == '2':
                    end_child_thread()
                    key_listener.stop()
                    print(f"停止工作线程{worker_thread}")
                    print(f"停止监听线程{key_listener}")
                    exit_program = True
                    break
                else:
                    pass
                time.sleep(0.1)
            if not result_queue.empty():
                result = result_queue.get()
                print("主线程获取的子线程结果:", result)
            else:
                pass
    except Exception as e:
        print("Exception caught:", e)
        traceback.print_exc()  # 打印详细的异常堆栈信息
        end_child_thread()
        key_listener.stop()
        print(f"except工作线程{worker_thread}")
        print(f"except监听线程{key_listener}")

    # 主线程退出
    logger.info(f"Main thread {main_thread_id} is exiting~")

使用网络调试助手向程序发送指令,运行效果如下:

 

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/921721.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

齐聚众力,中国移动以“百川”定乾坤

近日,由工业和信息化部、宁夏回族自治区人民政府主办的2023中国算力大会在宁夏银川举办。中国移动党组书记、董事长杨杰参加开幕式,并在大会主论坛作题为《算网筑基锻引擎 数实融合创未来》的主旨演讲。在演讲中,杨杰表示:未来&am…

牛客OJ 把字符串转换成整数

⭐️ 题目描述 🌟 O链接 https://www.nowcoder.com/practice/1277c681251b4372bdef344468e4f26e?tpId13&&tqId11202&rp6&ru/activity/oj&qru/ta/coding-interviews/question-ranking 思路: 首先需要检查第一位是否有符号位&#x…

【EA-ISET协会】Elsevier|2区智慧农业类SCIEI, 进展顺,3个月左右录用~

一、期刊简介 2区智慧农业类SCI&EI 【期刊简介】IF: 3.0-4.0, JCR2区, 中科院4区; 【检索情况】SCI&EI双检,正刊; 【终审周期】走期刊部系统,3个月左右录用; 二、征稿范围 大数据和遥感技术在智慧农业中…

Blender文件云端GPU渲染

本文介绍如何在 GPU云平台vast.ai 上渲染Blender动画的技术指南,假设你已使用 vast.ai 并知道如何启动实例,这里的重要步骤是为实例选择正确的映像。 推荐:用 NSDT编辑器 快速搭建可编程3D场景 使用 nvidia/cuda:11.4.1-cudnn8-devel-ubuntu2…

C++信息学奥赛1138:将字符串中的小写字母转换成大写字母

#include<bits/stdc.h> using namespace std; int main() {string arr;// 输入一行字符串getline(cin, arr);for(int i0;i<arr.length();i){if(arr[i]>97 and arr[i]<122){char aarr[i]-32; // 将小写字母转换为大写字母cout<<a; // 输出转换后的字符}els…

AI教学赋能计划(大模型特辑)2023秋季学期启动申请!

AI教学赋能计划是由百度飞桨发起&#xff0c;面向高校提供产教融合人才培养方案&#xff0c;一站式助力高校复合型人才培养&#xff0c;截至目前已经培养5200名AI专业师资&#xff0c;助力484所高校开设人工智能与AIX特色课程。 2023年随着文心一言等预训练大语言模型发展&…

中国平台软件市场研究报告:OceanBase为金融行业国产分布式数据库销售额第一

近日&#xff0c;《2022-2023年度中国平台软件市场研究报告》&#xff08;以下简称“报告”&#xff09;发布&#xff0c;报告对包括数据库、操作系统等在内的平台软件市场发展进行了分析。报告指出&#xff0c;在对平台软件需求增长最快的金融行业&#xff0c;OceanBase已占据…

一文看懂 ISP pipeline

文章目录 概述什么是ISPISP实现方案 ISP PipelineISP输入行缓冲数据对齐 难理解的关键算法WDR图像压缩色调映射 Tone MappingRAW域处理镜头阴影校正 LSC降噪&#xff1a;空域滤波器 Spatial FilterBayer Demosaic 概述 什么是ISP 主流的CMOS和CCD sensor基本都是输出Bayer Mo…

金佰利Kimberly-Clark直连EDI解决方案

Kimberly-Clark 金佰利是全球健康卫生护理领域的领导者。 成立于1872年的金佰利公司是全球健康卫生护理领域的行业领导者。个人健康护理用品、家庭生活用纸和商用消费产品是金佰利公司三大核心业务。金佰利在全球35个国家设有生产设施&#xff0c;产品销往超过175个国家和地区…

真机和开发者工具如何模拟虚拟定位

二、如何模拟虚拟定位 微信开发者如何模拟虚拟定位 1、打开微信开发者工具 2、打开调试器 3、切换到Sensor 4、勾选Enable 5、填写经纬度数值&#xff0c;在线解析经纬度链接&#xff1a;【经纬度查询】在线地图经度纬度查询|经纬度地名坐标转换 6、重新编译&#xff0c…

8月23日上课内容 第二章 MySQL数据库管理

本章结构&#xff1a; 数据库基本操作 查看数据库的结构 查看数据库列表信息 show database 查看数据库中的表信息 use 数据库名#切换到数据库中 show tables show tables in mysgl 显示数据表的结构(字段) describe user; Field:字段名称type: 数据类型Nul1 :是否允许为空Key…

c++多种情况不同概率下,在范围内使用随机数

多种情况不同概率下&#xff0c;在范围内使用随机数。比如有5种情况&#xff0c;每种情况的概率不相同&#xff0c;有的概率为25&#xff0c;有的为15. 使用random库的函数来生成随机数。 std::random_device rd; //产生随机数种子 std::mt19937 gen(rd()); //生成伪随机数&a…

VScode 编辑器报错: ‘HelloWorld‘ is declared but its value is never read.

.vue文件被标识红色波浪线&#xff1b;提示&#xff1a; HelloWorld is declared but its value is never read. 问题原因&#xff1a; 因为vue3已经不支持vetur插件。 1、在扩展里面进行搜索Vetur插件&#xff0c;进行禁用或卸载&#xff1b; 2、在 VScode扩展里面搜索并下载…

NO.08 MyBatis创建逆向工程

目录 1、前言 2、添加依赖和插件 3、创建MyBatis的核心配置文件 4、创建逆向工程的配置文件 5、执行MBG插件的generate目标 1、前言 工程的创建有正向工程和逆向工程之分。正向工程&#xff1a;先创建Java实体类&#xff0c;由框架负责根据实体类生成数据库表&#xff0c;如…

Vue3+Pinia+Koa+Three.js 全栈电商项目总结复盘

前言 前几天一个朋友去义乌旅游&#xff0c;带回来很多小商品&#xff0c;就是一整个物美价廉&#xff0c;但是为什么线下购物和网购有的时候差别这么大&#xff08;网购经常要退换货啊&#x1f62d;&#x1f62d;&#x1f62d;&#xff09;&#xff0c;为此我萌生了一个想法&…

SQL注入之宽字节注入

文章目录 宽字节注入是什么&#xff1f;注入练习让转义符失效联合查询 代码审计 宽字节注入是什么&#xff1f; 宽字节注入准确来说不是注入手法&#xff0c;而是另外一种比较特殊的情况。宽字节注入的目的是绕过单双引号转义。 宽字节注入是一种绕过单双引号转义的手段&#x…

数学——七桥问题——图论

当涉及数学&#xff0c;有很多不同的话题可以讨论。你是否有特定的数学领域、概念或问题想要了解更多&#xff1f;以下是一些常见的数学领域和主题&#xff0c;你可以选择一个或者告诉我你感兴趣的具体内容&#xff0c;我将很乐意为你提供更多信息&#xff1a; 代数学&#xff…

嵌入式Linux开发实操(十):ADC接口开发

#前言 ADC就是模数转换,可以用来接一些模拟量设备,所谓模拟量就是波形不是方波而是各种包络形状的波形的信号,比如电压、电流等电信号或压力、温度、湿度、位移、声音等非电信号,ADC就是将这些信号转换为数字方波信号,以便于信息传递的。 #ADC硬件设计 key按键连接了AD…

高学历就不会“造假”?

一直以来&#xff0c;学历都是职场的敲门砖&#xff0c;也是一个门槛。对企业的雇佣决策而言&#xff0c;学历有着重要的参考价值。 但是总有一小部分求职者&#xff0c;存在侥幸心理&#xff0c;想凭借假学历升职加薪、牟取利益&#xff0c;给企业带来不少的潜在用工风险。倒…