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

2024-08-26 00:44

本文主要是介绍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)

这篇关于python之多线程和多进程以及threading和multiprocessing模块的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1107065

相关文章

python使用fastapi实现多语言国际化的操作指南

《python使用fastapi实现多语言国际化的操作指南》本文介绍了使用Python和FastAPI实现多语言国际化的操作指南,包括多语言架构技术栈、翻译管理、前端本地化、语言切换机制以及常见陷阱和... 目录多语言国际化实现指南项目多语言架构技术栈目录结构翻译工作流1. 翻译数据存储2. 翻译生成脚本

如何通过Python实现一个消息队列

《如何通过Python实现一个消息队列》这篇文章主要为大家详细介绍了如何通过Python实现一个简单的消息队列,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下... 目录如何通过 python 实现消息队列如何把 http 请求放在队列中执行1. 使用 queue.Queue 和 reque

Python如何实现PDF隐私信息检测

《Python如何实现PDF隐私信息检测》随着越来越多的个人信息以电子形式存储和传输,确保这些信息的安全至关重要,本文将介绍如何使用Python检测PDF文件中的隐私信息,需要的可以参考下... 目录项目背景技术栈代码解析功能说明运行结php果在当今,数据隐私保护变得尤为重要。随着越来越多的个人信息以电子形

使用Python快速实现链接转word文档

《使用Python快速实现链接转word文档》这篇文章主要为大家详细介绍了如何使用Python快速实现链接转word文档功能,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下... 演示代码展示from newspaper import Articlefrom docx import

Python Jupyter Notebook导包报错问题及解决

《PythonJupyterNotebook导包报错问题及解决》在conda环境中安装包后,JupyterNotebook导入时出现ImportError,可能是由于包版本不对应或版本太高,解决方... 目录问题解决方法重新安装Jupyter NoteBook 更改Kernel总结问题在conda上安装了

Python如何计算两个不同类型列表的相似度

《Python如何计算两个不同类型列表的相似度》在编程中,经常需要比较两个列表的相似度,尤其是当这两个列表包含不同类型的元素时,下面小编就来讲讲如何使用Python计算两个不同类型列表的相似度吧... 目录摘要引言数字类型相似度欧几里得距离曼哈顿距离字符串类型相似度Levenshtein距离Jaccard相

SpringBoot中使用 ThreadLocal 进行多线程上下文管理及注意事项小结

《SpringBoot中使用ThreadLocal进行多线程上下文管理及注意事项小结》本文详细介绍了ThreadLocal的原理、使用场景和示例代码,并在SpringBoot中使用ThreadLo... 目录前言技术积累1.什么是 ThreadLocal2. ThreadLocal 的原理2.1 线程隔离2

Python安装时常见报错以及解决方案

《Python安装时常见报错以及解决方案》:本文主要介绍在安装Python、配置环境变量、使用pip以及运行Python脚本时常见的错误及其解决方案,文中介绍的非常详细,需要的朋友可以参考下... 目录一、安装 python 时常见报错及解决方案(一)安装包下载失败(二)权限不足二、配置环境变量时常见报错及

Python中顺序结构和循环结构示例代码

《Python中顺序结构和循环结构示例代码》:本文主要介绍Python中的条件语句和循环语句,条件语句用于根据条件执行不同的代码块,循环语句用于重复执行一段代码,文章还详细说明了range函数的使... 目录一、条件语句(1)条件语句的定义(2)条件语句的语法(a)单分支 if(b)双分支 if-else(

Python itertools中accumulate函数用法及使用运用详细讲解

《Pythonitertools中accumulate函数用法及使用运用详细讲解》:本文主要介绍Python的itertools库中的accumulate函数,该函数可以计算累积和或通过指定函数... 目录1.1前言:1.2定义:1.3衍生用法:1.3Leetcode的实际运用:总结 1.1前言:本文将详