1. 程式人生 > >python 多執行緒的理解

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())

執行結果為:

在結果中,可以清楚的看出來,一共花了兩秒,比之前的單程序節約了時間。這就是多執行緒存在的意義和價值。