线程是 Python 中实现并发的一种方式,它允许你在同一程序中同时执行多个任务。本教程将介绍 Python 线程的基础知识,包括如何创建线程、同步线程以及线程间的通信。

创建线程

在 Python 中,你可以使用 threading 模块来创建线程。以下是一个简单的例子:

import threading

def print_numbers():
    for i in range(5):
        print(i)

# 创建线程
t = threading.Thread(target=print_numbers)

# 启动线程
t.start()

# 等待线程完成
t.join()

同步线程

当多个线程访问共享资源时,可能会发生竞态条件。为了避免这种情况,你可以使用锁(Lock)来同步线程。

import threading

# 创建锁
lock = threading.Lock()

def print_numbers():
    for i in range(5):
        with lock:
            print(i)

# 创建线程
t = threading.Thread(target=print_numbers)

# 启动线程
t.start()

# 等待线程完成
t.join()

线程间通信

线程间可以通过队列(Queue)来通信。以下是一个使用队列的例子:

import threading

# 创建队列
queue = threading.Queue()

def producer():
    for i in range(5):
        queue.put(i)

def consumer():
    while True:
        item = queue.get()
        if item is None:
            break
        print(item)
        queue.task_done()

# 创建生产者和消费者线程
p = threading.Thread(target=producer)
c = threading.Thread(target=consumer)

# 启动线程
p.start()
c.start()

# 等待生产者完成
p.join()

# 通知消费者线程退出
queue.put(None)
c.join()

更多关于 Python 线程的内容,请参考Python 线程教程

图片示例

线程就像在高速公路上行驶的汽车,每个线程都是一辆汽车,它们在各自的路上行驶,但有时需要停下来等待其他车辆。以下是一个形象的比喻:

Thread_Analogy