《Python》Threading库详解:线程与多线程实战指南
文章目录
threading简介
threading 是 Python 标准库中用于实现多线程编程的模块。多线程编程允许程序同时执行多个任务,提高程序的并发性能,尤其适用于 I/O 密集型任务,例如网络请求、文件读写等。、
threading基本概念
常用类和方法
方式一:直接实例化 Thread 类
import threading
# 定义一个函数作为线程要执行的任务
def print_numbers():
for i in range(5):
print(f"Number: {i}")
# 创建线程对象
thread = threading.Thread(target=print_numbers)
# 启动线程
thread.start()
# 等待线程执行完毕
thread.join()
print("Main thread finished.")
结果:
方式二:继承 Thread 类
import threading
# 自定义线程类,继承自 threading.Thread
class MyThread(threading.Thread):
def run(self):
for i in range(5):
print(f"Number: {i}")
# 创建线程对象
thread = MyThread()
# 启动线程
thread.start()
# 等待线程执行完毕
thread.join()
print("Main thread finished.")
结果:
getName() 和 setName():用于获取和设置线程的名称。
import threading
def print_hello():
print(f"Hello from {threading.current_thread().getName()}")
thread = threading.Thread(target=print_hello)
thread.setName("MyThread")
thread.start()
thread.join()
is_alive():用于判断线程是否还在运行。
import threading
import time
def long_task():
time.sleep(2)
thread = threading.Thread(target=long_task)
thread.start()
print(f"Thread is alive: {thread.is_alive()}")
thread.join()
print(f"Thread is alive: {thread.is_alive()}")
线程同步
在多线程编程中,多个线程可能会同时访问和修改共享资源,这可能会导致数据不一致的问题。为了解决这个问题,threading 模块提供了一些同步机制。
Lock 是一种最基本的同步原语,用于确保同一时间只有一个线程可以访问共享资源。
import threading
# 创建一个锁对象
lock = threading.Lock()
shared_variable = 0
def increment():
global shared_variable
for _ in range(100000):
# 获取锁
lock.acquire()
try:
shared_variable += 1
finally:
# 释放锁
lock.release()
threads = []
for _ in range(2):
thread = threading.Thread(target=increment)
threads.append(thread)
thread.start()
for thread in threads:
thread.join()
print(f"Shared variable: {shared_variable}")
import threading
# 创建一个可重入锁对象
rlock = threading.RLock()
def recursive_function():
rlock.acquire()
try:
print("Lock acquired")
recursive_function()
finally:
rlock.release()
thread = threading.Thread(target=recursive_function)
thread.start()
thread.join()
线程池
虽然 threading 模块本身没有直接提供线程池的功能,但可以使用 concurrent.futures 模块中的 ThreadPoolExecutor 来实现线程池。
import concurrent.futures
def square(x):
return x * x
with concurrent.futures.ThreadPoolExecutor(max_workers=3) as executor:
results = executor.map(square, [1, 2, 3, 4, 5])
for result in results:
print(result)
在上述代码中,ThreadPoolExecutor 用于创建一个线程池,max_workers 参数指定了线程池中的最大线程数。executor.map() 方法用于并行执行任务
实例
实例代码展示了 Python 中 threading 模块的基本使用,包括创建线程、启动线程以及向线程函数传递参数等操作。
import threading
def worker():
print('线程开始执行')
for i in range(5):
print(f'线程正在工作:{i}')
print('线程执行完毕')
thread = threading.Thread(target=worker)
thread.start()
print('***主线程继续执行***')
'''传递参数'''
def worker(name):
print(f'{name}线程开始执行')
for i in range(5):
print(f'{name}正在工作:{i}')
print(f'{name}线程执行完毕')
thread = threading.Thread(target=worker,args=('线程1',))
thread.start()
print('***主线程继续执行***')
import threading
import time
def run(n):
print('task', n)
time.sleep(1)
print('2s')
time.sleep(1)
print('1s')
time.sleep(1)
def run2(t):
time.sleep(t)
print(f'我等了{t}秒')
if __name__ == '__main__':
t1 = threading.Thread(target=run, args=('t1',))
t2 = threading.Thread(target=run, args=('t2',))
# 启动 t1 和 t2 线程
t1.start()
t2.start()
# 修正参数,传递整数秒数
t3 = threading.Thread(target=run2, args=(5,))
t4 = threading.Thread(target=run2, args=(8,))
# 启动 t3 线程
t3.start()
# 启动 t4 线程
t4.start()
# 主线程等待 10 秒
time.sleep(10)
print('开始倒计时')
结果:
作者:Kai HVZ