[Python学习篇] Python多线程

多线程

Python 多线程编程是一种在单个程序中同时执行多个线程的技术,主要用于提高程序的并发性和性能,尤其是在 I/O 操作频繁的场景下。Python 提供了 threading 模块来支持多线程编程。

基本概念

  • 线程:线程是一个独立的执行流,可以与其他线程并发运行。
  • 主线程:每个 Python 程序都有一个默认的主线程,程序从主线程开始运行。
  • 守护线程:守护线程在主线程结束时会自动退出,不会阻止程序终止。

Thread 类

用于创建和管理线程。

创建一个线程

语法:

threading.Thread(target, args=(), kwargs={}, daemon=None)

  • target: 线程执行的目标函数。
  • args: 传递给目标函数的参数(元组)。
  • kwargs: 传递给目标函数的关键字参数(字典)。
  • daemon: 设置为守护线程(布尔值)。
  • name: 设置线程名称。

示例:

python 复制代码
import threading

def print_numbers(max_num):
    print(f"线程名称:{threading.current_thread().name}")
    for i in range(1, max_num):
        print(i)

def print_letters():
    print(f"线程名称:{threading.current_thread().name}")
    for letter in 'ABCDE':
        print(letter)

# 创建线程
# thread1 = threading.Thread(target=print_numbers, args=(6,))
thread1 = threading.Thread(target=print_numbers, kwargs={'max_num': 6})
thread2 = threading.Thread(target=print_letters)

# 启动线程
thread1.start()
thread2.start()

# 修改线程名称
# thread2.name = "CustomThread2"

# 等待所有线程完成
thread1.join()
thread2.join()

print("所有线程执行完成")
  • start(): 启动线程并调用 run() 方法。
  • run(): 线程执行的代码,可以重写。
  • join(timeout=None): 阻塞主线程,直到调用 join 的线程结束或超时。

线程之间是共享全局变量的

python 复制代码
import threading

list1 = []

def add_data():
    for i in range(3):
        list1.append(i)
        print(f"添加数据:{i}")

def read_data():
    print(f"获取数据:{list1}")

thread1 = threading.Thread(target=add_data)
thread2 = threading.Thread(target=read_data)

thread1.start()
thread2.start()

互斥锁 Lock

线程共享数据会造成数据安全性问题。使用互斥锁解决。

Lock 类:用于线程同步,防止多个线程同时访问共享资源。

lock常用函数:

  • acquire(blocking=True, timeout=-1): 请求锁(加锁)。
  • release(): 释放锁。
python 复制代码
import threading

# 多个线程对全局变量进行自增
g_num = 0

# 创建一把互斥锁
lock = threading.Lock()

def task():
    global g_num

    # 对修改共享变量的代码进行加锁
    lock.acquire()  # 加锁

    for i in range(1000000):
        g_num += 1
    print(f"task {g_num}, 线程名称-{threading.current_thread().name}")

    # 共享变量操作完成后释放锁
    lock.release()  # 释放锁


thread1 = threading.Thread(target=task)
thread2 = threading.Thread(target=task)

thread1.start()
# thread1.join()    
thread2.start()
相关推荐
SeaTunnel23 分钟前
从 Python Script 地狱到标准化数据集成框架
大数据·开发语言·python·程序员·代码·seatunnel
深度研习笔记31 分钟前
OpenCV工业视觉实战09|项目EXE打包+工控机无环境部署+后台常驻运行,彻底脱离Python环境,完成项目最终交付
python·opencv·webpack
CCPC不拿奖不改名1 小时前
大模型推理架构与开源生态知识整理
数据库·windows·python·架构·langchain·开源·github
Marst Code1 小时前
(python)2026Plotly 库评估:交互式可视化到底值不值得引入?
开发语言·python
databook1 小时前
当散点图不够用时:用 t-SNE 可视化多维数据
python·数据分析·数据可视化
我的xiaodoujiao4 小时前
快速学习Python基础知识详细图文教程9--函数进阶
开发语言·python·学习·测试工具
weixin_408099674 小时前
2026 图片去水印 API 接口完全指南:一键去除图片水印(附 Python/Java/PHP/C# 示例)
java·python·php·图片处理·api调用·图片去水印·石榴智能
去码头整点薯条ing5 小时前
某当网登录滑块【协议+OCR】
爬虫·python·ocr
赶紧写完去睡觉6 小时前
Anaconda 创建虚拟环境与使用
python·pycharm·conda
迷途呀6 小时前
Python:函数中的参数类型
开发语言·笔记·python·langchain·nlp