Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Python

Đa luồng (Threading) trong Python

Thread là đơn vị thực thi độc lập được quản lý bởi scheduler của OS. Module threading cung cấp API cấp cao để tạo và quản lý thread.

Khi nào dùng đa luồng?

  • Các tác vụ I/O-bound (đọc/ghi file, request network, DB).
  • Cần chạy song song nhiều tác vụ độc lập.
  • Giữ responsive cho GUI khi xử lý nặng ở background.

Các hàm thông dụng

Ví dụ: Tạo thread tùy chỉnh

import threading

def trace_function():
    print("Passing the trace function")
    def profile():
        print("PROFILE THREAD: " + threading.current_thread().getName())
    threading.settrace(trace_function)
    threading.setprofile(profile)

class MyThread(threading.Thread):
    def __init__(self, thread_name, thread_ID):
        super().__init__()
        self.thread_name = thread_name
        self.thread_ID = thread_ID
    def run(self):
        print(self.thread_ID)
        print("ACTIVE THREADS:", threading.active_count())
        print("CURRENT THREAD:", threading.current_thread().getName())

my_thread1 = MyThread("PP", 500)
my_thread2 = MyThread("PythonProgram", 1000)
print("MAIN THREAD NAME:", threading.main_thread().getName())
print("MAIN THREAD IDENT:", threading.get_ident())
print("STACK SIZE:", threading.stack_size())

my_thread1.start()
my_thread2.start()
print("ENUMERATE:", threading.enumerate())
print("EXIT")

Lưu ý quan trọng (GIL)

Python có Global Interpreter Lock (GIL): tại một thời điểm chỉ có một thread thực thi bytecode Python. Do đó:

  • Đa luồng không tăng tốc tác vụ CPU-bound (tính toán nặng).
  • Dùng multiprocessing cho CPU-bound.
  • Đa luồng hiệu quả cho I/O-bound (network, disk, sleep).
HàmMô tả
threading.active_count()Số thread đang sống
threading.current_thread()Thread object hiện tại
threading.get_ident()ID định danh thread hiện tại
threading.enumerate()List tất cả thread đang sống
threading.main_thread()Main thread object
threading.settrace(func)Set trace function cho tất cả thread
threading.setprofile(func)Set profile function
threading.stack_size([size])Kích thước stack cho thread mới