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

python之多线程和多进程以及threading和multiprocessing模块

在 Python 中,多线程和多进程是实现并发编程的两种主要方式。多线程适用于 I/O 密集型任务,而多进程适用于 CPU 密集型任务。Python 提供了 threading 模块用于多线程编程,提供了 multiprocessing 模块用于多进程编程。

多线程

基本用法

使用 threading 模块可以创建和管理线程。以下是一个简单的多线程示例:

import threading
import timedef worker(name):print(f"Thread {name} starting")time.sleep(2)print(f"Thread {name} finishing")# 创建线程
thread1 = threading.Thread(target=worker, args=("A",))
thread2 = threading.Thread(target=worker, args=("B",))# 启动线程
thread1.start()
thread2.start()# 等待线程完成
thread1.join()
thread2.join()print("All threads finished")
线程锁

线程锁用于防止多个线程同时访问共享资源,避免竞争条件。以下是一个使用线程锁的示例:

import threadinglock = threading.Lock()
counter = 0def increment_counter():global counterfor _ in range(100000):with lock:counter += 1# 创建线程
threads = []
for i in range(10):thread = threading.Thread(target=increment_counter)threads.append(thread)thread.start()# 等待线程完成
for thread in threads:thread.join()print(f"Final counter value: {counter}")

多进程

基本用法

使用 multiprocessing 模块可以创建和管理进程。以下是一个简单的多进程示例:

import multiprocessing
import timedef worker(name):print(f"Process {name} starting")time.sleep(2)print(f"Process {name} finishing")# 创建进程
process1 = multiprocessing.Process(target=worker, args=("A",))
process2 = multiprocessing.Process(target=worker, args=("B",))# 启动进程
process1.start()
process2.start()# 等待进程完成
process1.join()
process2.join()print("All processes finished")
进程锁

进程锁用于防止多个进程同时访问共享资源,避免竞争条件。以下是一个使用进程锁的示例:

import multiprocessinglock = multiprocessing.Lock()
counter = multiprocessing.Value('i', 0)def increment_counter():for _ in range(100000):with lock:counter.value += 1# 创建进程
processes = []
for i in range(10):process = multiprocessing.Process(target=increment_counter)processes.append(process)process.start()# 等待进程完成
for process in processes:process.join()print(f"Final counter value: {counter.value}")

threading 模块

threading 模块用于在单个进程中创建和管理多个线程。线程是轻量级的,并且共享相同的内存空间。

参数
  1. target:

    • 类型: 可调用对象
    • 说明: 线程启动后要执行的函数或方法。
  2. name:

    • 类型: 字符串
    • 说明: 线程的名称。默认情况下,Python 会自动生成一个唯一的名称。
  3. args:

    • 类型: 元组
    • 说明: 传递给 target 函数的位置参数。
  4. kwargs:

    • 类型: 字典
    • 说明: 传递给 target 函数的关键字参数。
  5. daemon:

    • 类型: 布尔值
    • 说明: 如果设置为 True,则表示该线程是守护线程。当所有非守护线程结束时,程序将退出,即使守护线程仍在运行
示例
import threadingdef worker(arg1, arg2, kwarg1=None):print(f"Worker thread is running with arguments: {arg1}, {arg2}, {kwarg1}")# 创建线程,传递位置参数和关键字参数
thread = threading.Thread(target=worker,args=(10, 20),kwargs={'kwarg1': 'example'},name='MyWorkerThread',daemon=True
)# 启动线程
thread.start()# 等待线程完成
thread.join()
  • target=worker: 指定线程要执行的函数是 worker
  • args=(10, 20): 传递给 worker 函数的位置参数是 1020
  • kwargs={'kwarg1': 'example'}: 传递给 worker 函数的关键字参数是 kwarg1='example'
  • name='MyWorkerThread': 指定线程的名称为 MyWorkerThread
  • daemon=True: 将线程设置为守护线程。
基本用法
  1. 创建线程
import threadingdef worker():print("Worker thread is running")# 创建线程
thread = threading.Thread(target=worker)# 启动线程
thread.start()# 等待线程完成
thread.join()
  1. 使用子类创建线程
import threadingclass MyThread(threading.Thread):def run(self):print("MyThread is running")# 创建线程
thread = MyThread()# 启动线程
thread.start()# 等待线程完成
thread.join()
  1. 线程同步

使用 threading.Lock 来确保线程安全。

import threadinglock = threading.Lock()def worker():with lock:# 线程安全的代码块print("Worker thread is running")# 创建多个线程
threads = [threading.Thread(target=worker) for _ in range(5)]# 启动所有线程
for thread in threads:thread.start()# 等待所有线程完成
for thread in threads:thread.join()

multiprocessing 模块

multiprocessing 模块用于创建和管理多个进程。每个进程都有自己独立的内存空间,因此适用于 CPU 密集型任务。
multiprocessing 模块中,multiprocessing.Process 类用于创建和管理进程。与 threading.Thread 类似,multiprocessing.Process 也接受一些参数来配置进程的行为。以下是 multiprocessing.Process 的常用参数及其解释:

multiprocessing.Process 参数
  1. target:

    • 类型: 可调用对象
    • 说明: 进程启动后要执行的函数或方法。
  2. name:

    • 类型: 字符串
    • 说明: 进程的名称。默认情况下,Python 会自动生成一个唯一的名称。
  3. args:

    • 类型: 元组
    • 说明: 传递给 target 函数的位置参数。
  4. kwargs:

    • 类型: 字典
    • 说明: 传递给 target 函数的关键字参数。
  5. daemon:

    • 类型: 布尔值
    • 说明: 如果设置为 True,则表示该进程是守护进程。当所有非守护进程结束时,程序将退出,即使守护进程仍在运行。
示例
import multiprocessingdef worker(arg1, arg2, kwarg1=None):print(f"Worker process is running with arguments: {arg1}, {arg2}, {kwarg1}")# 创建进程,传递位置参数和关键字参数
process = multiprocessing.Process(target=worker,args=(10, 20),kwargs={'kwarg1': 'example'},name='MyWorkerProcess',daemon=True
)# 启动进程
process.start()# 等待进程完成
process.join()
  • target=worker: 指定进程要执行的函数是 worker
  • args=(10, 20): 传递给 worker 函数的位置参数是 1020
  • kwargs={'kwarg1': 'example'}: 传递给 worker 函数的关键字参数是 kwarg1='example'
  • name='MyWorkerProcess': 指定进程的名称为 MyWorkerProcess
  • daemon=True: 将进程设置为守护进程。
进程的启动和等待
  • process.start(): 启动进程,调用 worker 函数。
  • process.join(): 等待进程完成。在 process.join() 被调用之前,主进程会被阻塞。
进程间通信

multiprocessing 模块还提供了多种进程间通信的方式,如 QueuePipeValueArray 等。

使用 Queue 进行进程间通信
import multiprocessingdef worker(queue):queue.put("Message from worker")# 创建队列
queue = multiprocessing.Queue()# 创建进程
process = multiprocessing.Process(target=worker, args=(queue,))# 启动进程
process.start()# 等待进程完成
process.join()# 获取队列中的消息
message = queue.get()
print(message)
使用 Pipe 进行进程间通信
import multiprocessingdef worker(conn):conn.send("Message from worker")conn.close()# 创建管道
parent_conn, child_conn = multiprocessing.Pipe()# 创建进程
process = multiprocessing.Process(target=worker, args=(child_conn,))# 启动进程
process.start()# 等待进程完成
process.join()# 获取管道中的消息
message = parent_conn.recv()
print(message)

通过这些参数和通信方式,你可以灵活地配置和管理进程的行为,并实现进程间的通信。

基本用法
  1. 创建进程
import multiprocessingdef worker():print("Worker process is running")# 创建进程
process = multiprocessing.Process(target=worker)# 启动进程
process.start()# 等待进程完成
process.join()
  1. 使用子类创建进程
import multiprocessingclass MyProcess(multiprocessing.Process):def run(self):print("MyProcess is running")# 创建进程
process = MyProcess()# 启动进程
process.start()# 等待进程完成
process.join()
  1. 进程间通信

使用 multiprocessing.Queuemultiprocessing.Pipe 进行进程间通信。

import multiprocessingdef worker(queue):queue.put("Message from worker")# 创建队列
queue = multiprocessing.Queue()# 创建进程
process = multiprocessing.Process(target=worker, args=(queue,))# 启动进程
process.start()# 等待进程完成
process.join()# 获取队列中的消息
message = queue.get()
print(message)
  1. 进程池

使用 multiprocessing.Pool 来管理进程池。

import multiprocessingdef worker(x):return x * x# 创建进程池
with multiprocessing.Pool(4) as pool:results = pool.map(worker, [1, 2, 3, 4, 5])print(results)

http://www.mrgr.cn/news/14725.html

相关文章:

  • 宠物空气净化器应该怎么选择?希喂、IAM、有哈哪款性价比高
  • linux neo4j 切换知识图谱
  • css之ShadowDOM
  • 第3章-04-Python库BeautifulSoup安装与讲解
  • HarmonyOS NEXT 实战开发:实现日常提醒应用
  • C#为复杂属性提供下拉式编辑框和弹出式编辑框
  • linux系统编程-网络-tcp(29)
  • 笔记本电脑中怎么查看光驱
  • Linux驱动学习之内核poll阻塞
  • 【C++ Primer Plus习题】6.5
  • 【项目日记】高并发内存池项目---整体框架设计
  • 鸿蒙ArkTS语言学习(五):扩展(函数)@Extend@Styles@Builder
  • 你的软件系统安全吗
  • class 2: vue.js 3 模板语法和内置指令
  • 在C语言中使用POSIX线程库(pthread)实现多线程编程
  • Amazon Bedrock 实践:零基础创建贪吃蛇游戏
  • 计算机毕业设计选题推荐-Cosplay论坛系统-Java/Python项目实战
  • gNB UE发送Timing AdvanceCommand
  • 闲置物品|基于SprinBoot+vue的校园闲置物品交易平台(源码+数据库+文档)
  • OpenCV绘图函数(7)从一个椭圆定义中提取出多边形的顶点坐标函数ellipse2Poly()的使用