python 多线程的理解

python多线程就是干(同时做两件事或者多件事),不只是python,很多编程语言都有多线程这个功能。我们一步一步来,先一心一用。

1、单线程(一心一用)

import time
import threading
# 左手画圆
def draw_circle(cost):
    print("start draw a circle ", time.ctime())
    time.sleep(cost)
    print("draw a circle ", time.ctime())
# 右手画方
def draw_square(cost):
    print("start draw a squre", time.ctime())
    time.sleep(cost)
    print("draw a squre ", time.ctime())
def single_thread():
    draw_circle(2)
    draw_square(3)
if __name__ == '__main__':
    print("start single_thread ", time.ctime())
    single_thread()
    print("end single_thread ", time.ctime())

运行的结果是:

start single_thread  Fri Aug 17 13:02:02 2018
start draw a circle  Fri Aug 17 13:02:02 2018
draw a circle  Fri Aug 17 13:02:04 2018
start draw a squre Fri Aug 17 13:02:04 2018
draw a squre  Fri Aug 17 13:02:07 2018
end single_thread  Fri Aug 17 13:02:07 2018

我们可以看到先画了圆花费2秒钟,后画了方花费3秒钟,总计花费5秒钟

2、多线程

引用了python的线程库:threading

可以通过spyder 编译器的命令窗口:help(threading)查看更多关于这个包的信息

好的,下面我们再来看一个程序吧。

import time
import threading
# 左手画圆
def draw_circle(cost):
    print("start draw a circle ", time.ctime())
    time.sleep(cost)
    print("draw a circle ", time.ctime())
# 右手画方
def draw_square(cost):
    print("start draw a squre", time.ctime())
    time.sleep(cost)
    print("draw a squre ", time.ctime())
def multi_thread():
    draw_circle_thread = threading.Thread(target=draw_circle, args=(1,))
    draw_square_thread = threading.Thread(target=draw_square, args=(2,))
    draw_circle_thread.start()
    draw_square_thread.start()
    draw_circle_thread.join()  // 调用 join 之后主线程会等待子线程运行完毕之后才会往下走
    draw_square_thread.join()  //
if __name__ == '__main__':
    print("start ", time.ctime())
    multi_thread()
    print("end ", time.ctime())

运行结果为:

python 多线程的理解_第1张图片

在结果中,可以清楚的看出来,一共花了两秒,比之前的单进程节约了时间。这就是多线程存在的意义和价值。

python 多线程的理解_第2张图片

 

你可能感兴趣的:(Python语言学习)