Technology Sharing

Python interview question: How to do multithreaded programming in Python?

2024-07-08

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

Multithreaded programming in Python is usually done using threading Module. Below is a simple example showing how to create and start multiple threads.

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