欢迎访问宙启技术站
智能推送

使用SimpleProgress()函数实现Python多线程任务的进度跟踪

发布时间:2024-01-18 16:33:31

在Python中,要实现多线程任务的进度跟踪,可以使用SimpleProgress()函数。该函数可以帮助我们跟踪多个线程的进度,并将进度信息打印到控制台。

以下是SimpleProgress()函数的实现代码:

import threading
import time

class SimpleProgress:
    def __init__(self, total_count):
        self.total_count = total_count
        self.completed_count = 0
        self.lock = threading.Lock()

    def increment(self):
        with self.lock:
            self.completed_count += 1

    def display_progress(self):
        while self.completed_count < self.total_count:
            progress = (self.completed_count / self.total_count) * 100
            print(f"Progress: {progress:.2f}%")
            time.sleep(1)

    def start_tracking(self):
        progress_thread = threading.Thread(target=self.display_progress)
        progress_thread.start()

以下是如何使用SimpleProgress()函数来跟踪多线程任务的进度的例子:

import threading
import time

def worker(progress):
    # 模拟耗时的任务
    time.sleep(2)
    progress.increment()

def main():
    num_threads = 10
    progress = SimpleProgress(num_threads)

    for _ in range(num_threads):
        thread = threading.Thread(target=worker, args=(progress,))
        thread.start()

    progress.start_tracking()

    # 等待所有线程完成
    main_thread = threading.currentThread()
    for thread in threading.enumerate():
        if thread is not main_thread:
            thread.join()

    print("All threads have finished.")

if __name__ == "__main__":
    main()

在上面的例子中,worker()函数模拟了一个耗时的任务,然后调用progress.increment()来增加已完成的计数。

main()函数中,我们创建了10个线程来执行工作任务,每个线程都将progress对象传递给worker()函数。在main()函数中,我们还启动了一个独立的线程来跟踪并打印进度信息。

最后,我们使用threading.enumerate()来等待所有线程完成,然后输出"所有线程已完成"的消息。

通过使用SimpleProgress()函数,我们可以很方便地实现多线程任务的进度跟踪,并及时获得任务的完成情况。