說到執行緒,我們要知道啥是序列,啥是並行程式
舉個例子:
序列程式,就是乙個乙個的執行程式
#python threading
import time
''' 每一秒中,輸出:this is a demo!
'''def serial():
'''序列輸出'''
time.sleep(1)
print('this is a demo!')
def main():
for i in range(5):
ser程式設計客棧ial()
if __name__ == '__main__':
main()
執行結果如下:
>>>
this is a demo!
this is a demo!
this is a demo!
this is a demo!
this is a demo!
>>>
並行程式,就是很多個程式在同一時間(巨集觀)一起執行
#python threading
import threading
import time
''' 並行執行,輸出:good!good!good!good!good!
'''def parallel():
'''並行輸出'''
time.sleep(1)
print('good!')
def main():
for i in range(5):
t = threading.thread(target=parallel)
t.start()
if __name__ == '__main__':
main()
當然我們通過執行程式,可以知道,並行程式要比序列程式執行的要快....
我們也可以獲取到當前的執行緒及個數:
#python threading
import threading
import time
''' 並行執行,輸出:
[, vsdujthread-1, started 660)>,
, ,, <_mainthread started>,
] 存在的執行緒數 : 7
good!good!good!good!good!
'''def pa
'''並行輸出'''
time.sleep(1)
print('good!')
def main():
for i in rangwww.cppcns.come(5):
t = threading.thread(target=parallel)
t.start()
if __name__ == '__main__':
main()
print(threading.enumerate())
print('存在的執行緒數 : %d'%threading.active_count())
執行結果如下:
>>>
[, , , www.cppcns.comrted 14512)>, , <_mainthread started>, ]
存在的執行緒數 : 7
>>> good!good!good!good!good!
本文標題: python開發之thread執行緒基礎例項入門
本文位址:
python的thread和threading區別
python提供了多種模組用來支援多執行緒程式設計,thread 在python3中改名為 thread threading,和 queue模組。通過加入queue模組,使用者可以建立多個執行緒共享資料的佇列資料結構。thread和threading模組都可以用來建立和管理執行緒,而thread模組...
python 多執行緒thread
python通過thread模組支援多執行緒,語法也很簡潔,現在通過乙個例項來看一下python中的多執行緒 import thread import time 保證只額外啟動乙個執行緒 isrunning false 啟動的時間控制,測試時間是23點44分,所以定的是這個時間,可以用於指定定時任務...
Python多執行緒Thread
import threading import time import random def worker name print name 開始執行.n 0 while true print name 輸出 str n n n 1 t random.randint 0,5 print name 休眠...