python3.x - python 代码运行顺序问题?

查看:157
本文介绍了python3.x - 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 之类的信息

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

解决方案

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)

这篇关于python3.x - python 代码运行顺序问题?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆