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

Chạy song song tác vụ trong Python

Nếu chương trình Python có thể chia thành các chương trình con độc lập, có thể chạy song song. Khái niệm: xử lý song song (parallel processing).

Với multiprocessing

Module multiprocessing tạo nhiều tiến trình con chạy song song. Khởi tạo Process, dùng run() và start()/join(). Dùng sleep để quan sát độ trễ.

Ví dụ

import multiprocessing
import time

class Process(multiprocessing.Process):
    def __init__(self, id):
        super(Process, self).__init__()
        self.id = id
    def run(self):
        time.sleep(1)
        print(f"Running process id: {self.id}")

if __name__ == '__main__':
    p = Process("a")
    p.start()
    p.join()
    p = Process("b")
    p.start()
    p.join()
    p = Process("c")
    p.start()
    p.join()

Kết quả

Running process id: a
Running process id: b
Running process id: c

Lưu ý: ví dụ dùng start/join tuần tự, không thực sự song song. Để song song thực sự, cần start tất cả trước rồi join.