Python中threading模块的常用方法和示例
Hi,大家好!这里是肆十二!
Python的threading模块提供了多线程编程的能力,允许在同一时间内执行多个线程。下面是threading模块的一些常用方法和示例:
1. Thread类
Thread类是threading模块的主要类,用于表示一个线程。
常用方法:
-
__init__(self, group=None, target=None, name=None, args=(), kwargs={}, daemon=None): 构造函数,创建一个新的线程对象。
target: 线程要执行的函数。name: 线程名。args: 传递给目标函数的参数元组。kwargs: 传递给目标函数的参数字典。daemon: 设置线程是否为守护线程。
-
start(): 开始执行线程。 -
run(): 定义线程功能的方法(通常在子类中重写)。 -
join(timeout=None): 等待线程终止。 -
is_alive(): 返回线程是否还存活。 -
setName(name): 设置线程名。 -
getName(): 获取线程名。
示例:
import threading
import time
def worker(number):
print(f"Worker {number} is starting.")
time.sleep(2)
print(f"Worker {number} is done.")
# 创建线程对象
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("All workers are done.")
2. Lock(锁)
Lock类用于同步线程,防止同时访问共享资源。
常用方法:
acquire(blocking=True, timeout=-1): 获取锁。release(): 释放锁。
示例:
import threading
counter = 0
lock = threading.Lock()
def increment_counter():
global counter
with lock:
counter += 1
threads = []
for _ in range(1000):
t = threading.Thread(target=increment_counter)
threads.append(t)
t.start()
for t in threads:
t.join()
print(f"Final Counter: {counter}")
3. Condition(条件变量)
Condition类用于线程间的协调,允许线程等待特定条件发生。
常用方法:
acquire(): 获取锁。release(): 释放锁。wait(timeout=None): 等待条件变量。notify(n=1): 通知一个或多个等待的线程。notifyAll(): 通知所有等待的线程。
示例:
import threading
class ProducerConsumer:
def __init__(self):
self.condition = threading.Condition()
self.items = []
def producer(self):
with self.condition:
for i in range(5):
print(f"Producing item {i}")
self.items.append(i)
self.condition.notify()
self.condition.wait()
def consumer(self):
with self.condition:
while True:
self.condition.wait()
if self.items:
item = self.items.pop(0)
print(f"Consuming item {item}")
self.condition.notify()
else:
break
# 使用示例
pc = ProducerConsumer()
producer_thread = threading.Thread(target=pc.producer)
consumer_thread = threading.Thread(target=pc.consumer)
producer_thread.start()
consumer_thread.start()
producer_thread.join()
consumer_thread.join()
4. 其他常用方法和类
threading.active_count(): 返回当前活动的线程数。threading.currentThread(): 返回当前的线程对象。threading.enumerate(): 返回当前所有线程对象的列表。threading.settrace(func): 为所有线程设置一个跟踪函数。threading.setprofile(func): 为所有线程设置一个配置文件函数。threading.Local(): 创建一个线程局部对象。
请注意,上述示例仅用于说明目的,并未考虑所有可能的边界情况和错误处理。在实际应用中,应根据需求调整和完善代码。
本文介绍了Pythonthreading模块中的主要类Thread、Lock和Condition,以及它们的常用方法。通过示例展示了如何创建和管理线程,以及如何同步和协调线程操作。
1426

被折叠的 条评论
为什么被折叠?



