在 Python 中进行多线程编程通常使用 threading
模块。下面是一个简单的示例,展示了如何创建和启动多个线程。
示例代码
import threading
import time# 定义一个简单的函数,它将在线程中运行
def print_numbers():for i in range(10):print(f"Number: {i}")time.sleep(1)def print_letters():for letter in "abcdefghij":print(f"Letter: {letter}")time.sleep(1)# 创建线程对象
thread1 = threading.Thread(target=print_numbers)
thread2 = threading.Thread(target=print_letters)# 启动线程
thread1.start()
thread2.start()# 等待线程完成
thread1.join()
thread2.join()print("All threads have finished execution")
代码解释
-
导入模块:
import threading import time
threading
模块提供了线程支持,而time
模块用于在线程中引入延迟。 -
定义线程函数:
def print_numbers():for i in range(10):print(f"Number: {i}")time.sleep(1)def print_letters():for letter in "abcdefghij":print(f"Letter: {letter}")time.sleep(1)
这两个函数将在不同的线程中运行,每个函数都会打印一个序列,并在每次打印后暂停一秒钟。
-
创建线程对象:
thread1 = threading.Thread(target=print_numbers) thread2 = threading.Thread(target=print_letters)
threading.Thread
创建一个新的线程对象,target
参数指定线程应运行的函数。 -
启动线程:
thread1.start() thread2.start()
调用
start()
方法以开始线程的执行。 -
等待线程完成:
thread1.join() thread2.join()
调用
join()
方法等待线程完成。这确保主程序在继续执行之前等待所有线程结束。 -
线程完成后的打印语句:
print("All threads have finished execution")
这句在所有线程结束后打印确认信息。
注意事项
- 线程安全:在多线程编程中,如果多个线程同时访问共享资源,可能会出现竞争条件,需要使用锁(
threading.Lock
)来确保线程安全。 - GIL(全局解释器锁):由于 Python 的 GIL 的存在,多线程在 CPU 密集型任务中并不能真正并行执行,推荐使用
multiprocessing
模块来绕过 GIL 限制以实现真正的并行执行。
如果你有更具体的需求或者需要处理更复杂的多线程任务,可以进一步探索 threading
模块的其他功能,如 Lock
、Semaphore
、Event
等。