python 多執行緒thread

2021-06-17 17:35:23 字數 2222 閱讀 8254

python通過thread模組支援多執行緒,語法也很簡潔,現在通過乙個例項來看一下python中的多執行緒:

import thread

import time

#保證只額外啟動乙個執行緒

isrunning=false

#啟動的時間控制,測試時間是23點44分,所以定的是這個時間,可以用於指定定時任務的執行時間

timer_hour=23

timer_min=44

#額外其他乙個執行緒處理任務

def another_thread():

print '[another_thread] is start...'

#宣告使用全域性變數isrunning

global isrunning

#for迴圈模擬任務執行

for i in range(3):

time.sleep(1)

print '[another_thread] time: %s ' % time.strftime('%y-%m-%d %x',time.localtime())

print '[another_thread] is running: %s' % isrunning

#此處只是為了保證該任務一天只啟動一次,一分不會超過60秒

time.sleep(60)

print '[another_thread] is end...'

#該狀態只是為了保證該任務不會重複啟動,當然對於任務可以設定乙個超時時間,到時不結束自動終結

isrunning = false

if __name__ == '__main__':

while true:

now = time.localtime()

print '[main_thread] time: %s' % time.strftime('%y-%m-%d %x',now)

print '[main_thread] is running: %s' % isrunning

if now.tm_hour==timer_hour and now.tm_min==timer_min and not isrunning:

#進入任務前即置為true狀態,防止重複啟動

isrunning = true

#python開啟乙個新的執行緒,從後面列印日誌的情況可以知道,並不會影響主線程的執行

thread.start_new_thread(another_thread,())

time.sleep(1)

**執行後如下:

c:\users\captain\desktop>python task.py

[main_thread] time: 2013-07-31 23:44:56

[main_thread] is running: false

[another_thread] is start...

[main_thread] time: 2013-07-31 23:44:57[another_thread] time: 2013-07-31 23:44:57

[main_thread] is running: true[another_thread] is running: true

[main_thread] time: 2013-07-31 23:44:58[another_thread] time: 2013-07-31 23:44:58

[main_thread] is running: true[another_thread] is running: true

[main_thread] time: 2013-07-31 23:44:59[another_thread] time: 2013-07-31 23:44:59

[another_thread] is running: true[main_thread] is running: true

[main_thread] time: 2013-07-31 23:45:00

[main_thread] is running: true

[main_thread] time: 2013-07-31 23:45:01

[main_thread] is running: true

[main_thread] time: 2013-07-31 23:45:02

該例項很簡單,可按照這個思路,應用於定時任務,心跳檢測,守護程序等實際場景中

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 休眠...

python多執行緒使用thread

import sched import threading import time defnew task function,delay time,args 定時任務函式 param function 需要執行的函式 param delay time 延遲多少時間執行 param args 需要給f...

python多執行緒之 thread

多執行緒類似於同時執行多個不同程式,多執行緒執行有如下優點 執行緒在執行過程中與程序還是有區別的。每個獨立的執行緒有乙個程式執行的入口 順序執行序列和程式的出口。但是執行緒不能夠獨立執行,必須依存在應用程式中,由應用程式提供多個執行緒執行控制。每個執行緒都有他自己的一組cpu暫存器,稱為執行緒的上下...