当前位置: 首页 > news >正文

广西水利工程建设管理网站网站建设项目费用报价

广西水利工程建设管理网站,网站建设项目费用报价,网件r6300v2,深圳招工网站Python 多线程基础概念多线程允许程序在同一时间执行多个任务,适用于 I/O 密集型任务(如网络请求、文件读写)或需要并行处理的场景。Python 通过 threading 模块实现多线程,但由于全局解释器锁(GIL)的存在&…

Python 多线程基础概念

多线程允许程序在同一时间执行多个任务,适用于 I/O 密集型任务(如网络请求、文件读写)或需要并行处理的场景。Python 通过 threading 模块实现多线程,但由于全局解释器锁(GIL)的存在,多线程在 CPU 密集型任务中性能提升有限。

创建线程的两种方法

方法一:继承 threading.Thread

import threadingclass MyThread(threading.Thread):def __init__(self, thread_id, name):threading.Thread.__init__(self)self.thread_id = thread_idself.name = namedef run(self):print(f"线程 {self.name} 正在运行")# 创建线程实例
thread1 = MyThread(1, "Thread-1")
thread2 = MyThread(2, "Thread-2")# 启动线程
thread1.start()
thread2.start()# 等待线程结束
thread1.join()
thread2.join()
print("主线程退出")

方法二:直接使用 threading.Thread 构造函数

import threadingdef worker(name):print(f"线程 {name} 正在执行")# 创建线程
threads = []
for i in range(3):t = threading.Thread(target=worker, args=(f"Thread-{i}",))threads.append(t)t.start()# 等待所有线程完成
for t in threads:t.join()
print("所有线程执行完毕")

线程同步与锁机制

多线程共享全局变量时可能导致数据竞争,需使用锁(Lock)确保线程安全:

import threadingcounter = 0
lock = threading.Lock()def increment():global counterfor _ in range(100000):lock.acquire()counter += 1lock.release()threads = []
for _ in range(2):t = threading.Thread(target=increment)threads.append(t)t.start()for t in threads:t.join()
print(f"最终计数器值: {counter}")  # 正确输出 200000

线程间通信

通过 Queue 模块实现线程安全的数据交换:

import threading
import queue
import timedef producer(q):for i in range(5):time.sleep(1)q.put(f"产品 {i}")print(f"生产了 产品 {i}")def consumer(q):while True:item = q.get()if item is None:breakprint(f"消费了 {item}")q.task_done()q = queue.Queue()
producer_thread = threading.Thread(target=producer, args=(q,))
consumer_thread = threading.Thread(target=consumer, args=(q,))producer_thread.start()
consumer_thread.start()producer_thread.join()
q.put(None)  # 发送结束信号
consumer_thread.join()

线程池与高级用法

使用 concurrent.futures 简化线程管理:

from concurrent.futures import ThreadPoolExecutor
import urllib.requestdef download_url(url):with urllib.request.urlopen(url) as response:return f"{url}: {len(response.read())} 字节"urls = ["https://www.python.org","https://www.google.com","https://www.github.com"
]with ThreadPoolExecutor(max_workers=3) as executor:results = executor.map(download_url, urls)for result in results:print(result)

多线程与性能优化

GIL 的影响
Python 的全局解释器锁(GIL)确保同一时间只有一个线程执行字节码。对于 CPU 密集型任务,多线程可能无法提升性能,此时建议使用多进程(multiprocessing 模块)。

适用场景对比

  • 多线程:I/O 阻塞操作(如网络请求、文件读写)
  • 多进程:CPU 密集型计算(如数学运算、图像处理)

可视化示例

以下是一个简单的多线程执行流程图:

主线程
│
├─ 启动 Thread-1
│  └─ 执行任务 A
├─ 启动 Thread-2
│  └─ 执行任务 B
└─ 等待所有线程结束

完整代码示例

import threading
import timedef task(name, delay):print(f"任务 {name} 开始")time.sleep(delay)print(f"任务 {name} 完成")# 创建并启动线程
threads = [threading.Thread(target=task, args=("A", 2)),threading.Thread(target=task, args=("B", 1)),threading.Thread(target=task, args=("C", 3))
]for t in threads:t.start()# 等待线程结束
for t in threads:t.join()print("所有任务执行完毕")

注意事项

  • 避免死锁:确保锁的获取和释放成对出现。
  • 线程安全:使用 QueueLock 保护共享资源。
  • 异常处理:线程内的异常需在线程内捕获,否则会静默失败。

通过合理设计,多线程能显著提升程序响应速度,尤其是在涉及等待外部资源的场景中

http://www.dtcms.com/a/585387.html

相关文章:

  • Rust 练习册 :Phone Number与电话号码处理
  • CUDA C++编程指南(3.2.5)——分布式共享内存
  • 华为路由器核心技术详解:数据包的智能导航系统
  • Go基础:字符串常用的系统函数及对应案例详解
  • redis查询速度快的原因?
  • 社区类网站开发网站怎么提升流量
  • 注册网站时手机号格式不正确容易做的html5的网站
  • 如何查询哪些服务器 IP 访问了 Google Cloud 的 Vertex AI API
  • DataWhale-HelloAgents(第一部分:智能体与语言模型基础)
  • Ollama:在本地运行大语言模型的利器
  • 构建智能知识库问答助手:LangChain与大语言模型的深度融合实践
  • 大语言模型如何获得符号逻辑演绎能力?从频率范式到贝叶斯范式的转移
  • 网站建设中的功能新浪微博图床wordpress
  • 【玩泰山派】9、ubuntu22.04安装中文输入法
  • Spring IOC/DI 与 MVC 从入门到实战
  • SCNet超算平台DCU异构环境的Ollama启动服务后无法转发公网的问题解决
  • macOS下如何全文检索epub格式文件?
  • 一键配置 macOS 终极终端:iTerm2 + Oh My Zsh 自动化安装脚本
  • 如何在 Mac、Ubuntu、CentOS、Windows 上安装 MySQL 客户端
  • 石景山广州网站建设外贸soho建站多少钱
  • 某观鸟记录中心的爬虫——mitmproxy的简单使用
  • 58同城上海网站建设北京朝阳区房价
  • 金融网络销售怎么找客源公司网站做优化少钱
  • 代码随想录 Q84.分发饼干
  • 11.8 脚本网页 打砖块max
  • 终极笔记应用程序Alexandrie
  • 「嵌」入未来,「式」界无限 · 第5篇:能源电力的智能化跃迁
  • 自动化实践(7.25):把 PsTools 接入 PowerShell / 批处理 / Ansible
  • 太原在线网站建设深圳网站关键词优化
  • AWS Lambda的安全之道:S3静态加密与运行时完整性检查的双重保障