
Python3 多线程
发布日期:2021-05-14 05:44:50
浏览次数:15
分类:精选文章
本文共 3124 字,大约阅读时间需要 10 分钟。
Python3 多线程
多线程类似于同时执行多个不同程序,提供了显著的优势。首先,线程可以将占据长时间的任务放到后台处理,提升用户界面的响应速度。例如,用户点击按钮触发处理时,界面可以弹出进度条显示处理进度。其次,线程可以提高程序运行效率,特别是在涉及大量等待操作如文件读写和网络通信时,线程可以更好地释放资源如内存。最后,线程可以在执行过程中被抢占或暂停,这为程序设计提供了更高的灵活性。
需要注意的是,线程与进程有本质区别。每个线程都有自己的程序入口、执行顺序和程序出口,但线程无法独立运行,必须依赖应用程序提供执行控制。线程运行需要各自的上下文,包括CPU寄存器状态。在实际运行中,线程可以被抢占,即中断运行;也可以进入睡眠状态,等待其他线程或I/O操作完成。
线程模块
Python3 提供了两个主要线程模块:_thread和threading。其中thread模块已被废弃,threading模块提供了更高级别的功能,包括丰富的线程控制方法和线程同步机制。
使用threading模块创建线程
要使用threading模块创建线程,可以继承threading.Thread类并实现run方法。以下是一个示例:
from threading import Thread, enumerateimport timeclass MyThread(Thread): def __init__(self, name): super().__init__(name) self.count = 0 def run(self): while self.count < 5: time.sleep(1) print(f"{self.name}: {time.strftime('%Y-%m-%d %H:%M:%S')}") self.count += 1thread1 = MyThread("Thread-1")thread2 = MyThread("Thread-2")thread1.start()thread2.start()for thread in enumerate(): if thread.isAlive(): print(f"当前活跃线程:{thread.name}") else: print(f"当前逗号线程:{thread.name}")thread1.join()thread2.join()print("主线程退出")
线程同步
在多线程环境中共享数据时,为了确保数据一致性,必须使用同步机制。threading模块提供了ThreadLock和Rlock类,用于保护共享资源。以下是一个使用Rlock实现线程同步的示例:
from threading import Lock, enumerateimport timeclass MyThread(Thread): def __init__(self, name, lock): super().__init__(name) self.lock = lock self.count = 0 def run(self): while self.count < 5: self.lock.acquire() try: self.count += 1 print(f"{self.name}: {self.count}") finally: self.lock.release() time.sleep(1)lock = Lock()thread1 = MyThread("Thread-1", lock)thread2 = MyThread("Thread-2", lock)thread1.start()thread2.start()while True: time.sleep(1) breakthread1.join()thread2.join()print("主线程退出")
线程优先级队列(Queue)
当多个线程需要共享任务时,可以使用Queue模块来实现线程安全的数据传输。以下是一个使用队列实现任务分发的示例:
from queue import Queuefrom threading import Threadimport timeclass MyThread(Thread): def __init__(self, name, queue): super().__init__(name) self.queue = queue self.count = 0 def run(self): while self.count < 5: self.queue_lock.acquire() try: if not self.workQueue.empty(): data = self.workQueue.get() print(f"{self.name}处理{data}") self.count += 1 finally: self.queue_lock.release() time.sleep(1)lock = Lock()workQueue = Queue(maxsize=10)threadList = ["Thread-1", "Thread-2", "Thread-3"]for tName in threadList: thread = MyThread(tName, workQueue) thread.start()for word in ["One", "Two", "Three", "Four", "Five"]: lock.acquire() try: workQueue.put(word) finally: lock.release()while not workQueue.empty(): passexitFlag = 1for thread in enumerate(): if not thread.is_alive(): continue thread.join()print("主线程退出")
上述代码演示了如何在多线程环境中使用threading模块实现线程创建、线程同步和队列通信。通过合理使用线程和同步机制,可以有效地管理多线程环境,避免数据竞争和不一致,提升程序的整体性能。
发表评论
最新留言
很好
[***.229.124.182]2025年04月15日 21时25分37秒
关于作者

喝酒易醉,品茶养心,人生如梦,品茶悟道,何以解忧?唯有杜康!
-- 愿君每日到此一游!
推荐文章
MySQL错误日志(Error Log)
2019-03-06
解决:angularjs radio默认选中失效问题
2019-03-06
windows环境下安装zookeeper(仅本地使用)
2019-03-06
缓冲区溢出实例(一)--Windows
2019-03-06
Python中字符串前添加r ,b, u, f前缀的含义
2019-03-06
Hadoop学习笔记—Yarn
2019-03-06
JSONPath小试牛刀之Snack3
2019-03-06
Jenkins - 部署在Tomcat容器里的Jenkins,提示“反向代理设置有误”
2019-03-06
wxWidgets源码分析(3) - 消息映射表
2019-03-06
wxWidgets源码分析(5) - 窗口管理
2019-03-06
wxWidgets源码分析(7) - 窗口尺寸
2019-03-06
wxWidgets源码分析(8) - MVC架构
2019-03-06
wxWidgets源码分析(9) - wxString
2019-03-06
Mybatis Generator最完整配置详解
2019-03-06
[白话解析] 深入浅出熵的概念 & 决策树之ID3算法
2019-03-06
[梁山好汉说IT] 梁山好汉和抢劫银行
2019-03-06
[源码解析] 消息队列 Kombu 之 基本架构
2019-03-06
[源码分析] 消息队列 Kombu 之 启动过程
2019-03-06
[源码分析] 消息队列 Kombu 之 Consumer
2019-03-06
抉择之苦
2019-03-06