python 代码运行顺序问题?

有如下代码:

class Test:
    def a(self):
        time.sleep(random.uniform(1,3))
        print('a done')
    
    def b(self):
        time.sleep(random.uniform(1,3))
        print('b done')

    def c(self):
        time.sleep(random.uniform(1,3))
        print('C done')

想以多线程的方式运行, 并计算运行时间:

def main():
    task = Test()
    task_list = [
        task.a,
        task.b,
        task.c,
    ]
    for i in task_list:
        # i = run_time_log(i)
        t = Thread(target=i)
        t.start()


start = time.time()
main()
print(time.time() - start)

问题是,每次运行的时候都是先把最后的 print 弄出来,然后才会打印诸如 a done, b done 之类的信息

所以最终的问题是:如何可以正确的得到这段代码的运行时间,以及为什么会出现这种情况

阅读 2.4k
1 个回答

Thread.join([timeout])

Wait until the thread terminates. This blocks the calling thread until the thread whose join() method is called terminates – either normally or through an unhandled exception – or until the optional timeout occurs.

When the timeout argument is present and not None, it should be a floating point number specifying a timeout for the operation in seconds (or fractions thereof). As join() always returns None, you must call isAlive() after join() to decide whether a timeout happened – if the thread is still alive, the join() call timed out.

When the timeout argument is not present or None, the operation will block until the thread terminates.

A thread can be join()ed many times.

join() raises a RuntimeError if an attempt is made to join the current thread as that would cause a deadlock. It is also an error to join() a thread before it has been started and attempts to do so raises the same exception.

代码只需要加一行,代码如下:

import time
from threading import Thread
import random

class Test:
    def a(self):
        time.sleep(random.uniform(1,3))
        print('a done')

    def b(self):
        time.sleep(random.uniform(1,3))
        print('b done')

    def c(self):
        time.sleep(random.uniform(1,3))
        print('C done')

def main():
    task = Test()
    task_list = [
        task.a,
        task.b,
        task.c,
    ]
    for i in task_list:
        t = Thread(target=i)
        t.start()
        t.join()  # <-- 这里需要 join,主线程等待子线程执行完毕,没有就是你之前的情况


start = time.time()
main()
print(time.time() - start)
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进