Python编程:多线程、队列与异步操作

多线程 (Multithreading)

Python通过threading模块实现多线程编程,但由于GIL(全局解释器锁)的存在,多线程适合I/O密集型任务而非CPU密集型任务。

基本使用

import threading
import time

def worker(num):
    print(f"线程 {num} 开始")
    time.sleep(2)
    print(f"线程 {num} 结束")

threads = []
for i in range(5):
    t = threading.Thread(target=worker, args=(i,))
    threads.append(t)
    t.start()

for t in threads:
    t.join()  # 等待所有线程完成

print("所有线程执行完毕")

线程同步

from threading import Lock

lock = Lock()
shared_value = 0

def increment():
    global shared_value
    with lock:  # 自动获取和释放锁
        shared_value += 1

队列 (Queue)

队列是线程间通信的安全方式,Python提供了queue模块。

基本队列操作

from queue import Queue
import threading

def producer(q):
    for i in range(5):
        q.put(i)
        print(f"生产: {i}")
        time.sleep(0.5)

def consumer(q):
    while True:
        item = q.get()
        if item is None:  # 终止信号
            break
        print(f"消费: {item}")
        q.task_done()  # 标记任务完成

q = Queue()
prod_thread = threading.Thread(target=producer, args=(q,))
cons_thread = threading.Thread(target=consumer, args=(q,))

prod_thread.start()
cons_thread.start()

prod_thread.join()  # 等待生产者完成
q.put(None)  # 发送终止信号
cons_thread.join()

优先级队列

from queue import PriorityQueue

pq = PriorityQueue()
pq.put((3, "低优先级"))
pq.put((1, "高优先级"))
pq.put((2, "中优先级"))

while not pq.empty():
    print(pq.get()[1])  # 输出: 高优先级, 中优先级, 低优先级

异步操作 (Asyncio)

Python的asyncio模块提供了真正的异步I/O支持,适合高并发的网络操作。

基本异步函数

import asyncio

async def fetch_data():
    print("开始获取数据")
    await asyncio.sleep(2)  # 模拟I/O操作
    print("数据获取完成")
    return {"data": 123}

async def main():
    task = asyncio.create_task(fetch_data())
    print("执行其他操作")
    await task  # 等待任务完成
    print(f"获取到的数据: {task.result()}")

asyncio.run(main())

多任务并发

async def task(name, seconds):
    print(f"{name} 开始")
    await asyncio.sleep(seconds)
    print(f"{name} 完成")
    return f"{name} 结果"

async def main():
    results = await asyncio.gather(
        task("任务1", 2),
        task("任务2", 1),
        task("任务3", 3)
    )
    print(f"所有任务完成: {results}")

asyncio.run(main())

综合应用:多线程+队列+异步

import asyncio
import threading
from queue import Queue

def blocking_io(q):
    # 模拟阻塞I/O操作
    import time
    time.sleep(2)
    q.put("阻塞操作结果")

async def async_operation():
    loop = asyncio.get_running_loop()
    q = Queue()
    
    # 在单独线程中运行阻塞操作
    thread = threading.Thread(target=blocking_io, args=(q,))
    thread.start()
    
    # 异步等待结果
    while q.empty():
        await asyncio.sleep(0.1)
    
    result = q.get()
    thread.join()
    return result

async def main():
    result = await async_operation()
    print(f"最终结果: {result}")

asyncio.run(main())

实践建议

  1. 多线程:适合I/O密集型任务,需要与阻塞库交互时

  2. 队列:线程间安全通信,生产者-消费者模式

  3. 异步:高并发网络应用,现代Python异步库支持

注意:CPU密集型任务应考虑使用multiprocessing模块而非多线程。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值