python 多线程
Python 多线程是指在同一时间内,同时执行多个线程。Python 有内置的 threading 模块,可用于创建和管理线程。多线程在处理大量数据和执行 I/O 操作时特别有用,因为它允许同时执行多个任务,提高了程序的效率和性能。
在 Python 中创建线程的方法有两种:一种是继承 threading.Thread 类,另一种是传递一个可调用对象给 threading.Thread() 构造函数。下面是一个使用 threading.Thread 类的示例:
import threading
def worker():
print('Worker thread is running')
t = threading.Thread(target=worker)
t.start()
该示例中,worker() 函数是线程实际执行的代码,它被传递给 threading.Thread() 构造函数作为参数。调用 t.start() 方法启动线程。线程启动后,它将在后台运行,直到完成 worker() 函数中的所有操作或遇到异常。
Python 多线程还可以使用锁机制来避免不同线程同时访问共享资源,如下所示:
import threading
balance = 0
lock = threading.Lock()
def deposit(amount):
global balance
lock.acquire()
try:
balance += amount
finally:
lock.release()
def withdraw(amount):
global balance
lock.acquire()
try:
balance -= amount
finally:
lock.release()
t1 = threading.Thread(target=deposit, args=(100,))
t2 = threading.Thread(target=withdraw, args=(50,))
t1.start()
t2.start()
t1.join()
t2.join()
print('Final balance:', balance)
该示例中,deposit() 和 withdraw() 函数分别是向帐户存款和提款的函数,它们共享 balance 变量。这里使用了锁机制来避免两个线程同时访问 balance 变量。当一个线程获得锁时,其他线程必须等待直到锁被释放。在完成关键部分后,必须释放锁,以便其他线程可以获得它。
总之,Python 的多线程使程序可以同时执行多个任务,提高了程序的效率和性能。但是,在使用多线程时,必须小心处理共享资源和避免死锁等问题
原文地址: https://www.cveoy.top/t/topic/fptI 著作权归作者所有。请勿转载和采集!