python--threading 多執行緒的簡單應用
最近做一個基於itchat的微信機器人,涉及到了點多執行緒執行的事項。
基於itchat庫進行的機器人具有資訊監聽功能,程式碼如下。
@itchat.msg_register([TEXT],isFriendChat=True)
def message_reply(msg):
try:
FromUserName = msg['FromUserName']
except:
print('獲取FromUserName失敗')
# admins_username為管理員賬號的一個list
if FromUserName in admins_username:
if msg['Text'] == '更新資料':
cont0 = '開始更新資料'
print(cont0)
itchat.send_msg(msg=cont0, toUserName=FromUserName)
# 新建執行緒用來單獨執行更新程式
update_threading = threading.Thread(target=updatedata,args=('2',))
update_threading.start()
else:
message = "小助手執行正常,可以接收到資訊,請傳送指令:'更新選品庫' or '啟動傳送' "
itchat.send_msg(msg=message, toUserName=FromUserName)
itchat.auto_login(hotReload=True)
itchat.run()
itchat 通過itchat.run()會開啟監聽程式執行,這個時候如果直接在reply裡面執行一段長時間的程式,他會暫停掉監聽的功能,為了保證互相不影響,所以需要引入多執行緒。
方法就是
import threading
update_threading = threading.Thread(target=updatedata,args=('2',))
update_threading.start ()
這裡引數target = updatedata是名為updatedata的function,而args是加入的引數。然後使用start()他就可以單獨運行了。再通過微信命令呼叫執行其他程序的時候都可以這樣做,解決執行緒佔用的問題。
下面放一段相關的資料
threading用於提供執行緒相關的操作,執行緒是應用程式中工作的最小單元。python當前版本的多執行緒庫沒有實現優先順序、執行緒組,執行緒也不能被停止、暫停、恢復、中斷。
threading模組提供的類:
Thread, Lock, Rlock, Condition, [Bounded]Semaphore, Event, Timer, local。
threading 模組提供的常用方法:
threading.currentThread(): 返回當前的執行緒變數。
threading.enumerate(): 返回一個包含正在執行的執行緒的list。正在執行指執行緒啟動後、結束前,不包括啟動前和終止後的執行緒。
threading.activeCount(): 返回正在執行的執行緒數量,與len(threading.enumerate())有相同的結果。
threading 模組提供的常量:
threading.TIMEOUT_MAX 設定threading全域性超時時間。
Thread類
Thread是執行緒類,有兩種使用方法,直接傳入要執行的方法或從Thread繼承並覆蓋run():
建立執行緒的兩種方法
構造方法:
Thread(group=None, target=None, name=None, args=(), kwargs={})
group: 執行緒組,目前還沒有實現,庫引用中提示必須是None;
target: 要執行的方法;
name: 執行緒名;
args/kwargs: 要傳入方法的引數。
例項方法:
isAlive(): 返回執行緒是否在執行。正在執行指啟動後、終止前。
get/setName(name): 獲取/設定執行緒名。
start(): 執行緒準備就緒,等待CPU排程
is/setDaemon(bool): 獲取/設定是後臺執行緒(預設前臺執行緒(False))。(在start之前設定)
如果是後臺執行緒,主執行緒執行過程中,後臺執行緒也在進行,主執行緒執行完畢後,後臺執行緒不論成功與否,主執行緒和後臺執行緒均停止
如果是前臺執行緒,主執行緒執行過程中,前臺執行緒也在進行,主執行緒執行完畢後,等待前臺執行緒也執行完成後,程式停止
start(): 啟動執行緒。
join([timeout]): 阻塞當前上下文環境的執行緒,直到呼叫此方法的執行緒終止或到達指定的timeout(可選引數)。