Partage de technologie

Question d'entretien Python : Comment effectuer une programmation multithread en Python ?

2024-07-08

한어Русский языкEnglishFrançaisIndonesianSanskrit日本語DeutschPortuguêsΕλληνικάespañolItalianoSuomalainenLatina

Pour la programmation multithread en Python, il est courant d'utiliser threading module. Vous trouverez ci-dessous un exemple simple montrant comment créer et démarrer plusieurs threads.

Exemple de code

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")