『壹』 python theading 如何結束線程
其實時,如果主線程退出的話,其它子線程就可退出。
如果你要某些線程在運行一個閥值自動退出,你可以在線程裡面做一步運行時間檢測(或者循環次數檢測)。
『貳』 python 多線程 運維問題, 詳見問題補充 我寫了一段代碼 但感覺有問題,希望大俠能指點。
你這個腳本有些語法問題,不過總的設計思路是沒有問題的。 我已經用你的腳本執行了,輸入如下。我覺得可以講hosts.txt文件拆分成5個文件,每個文件含8條ip,按順序執行,這樣可以控制每次只處理8個ip,也就達到並發8台機子的要求。
python multhred.py "echo 'hello world'"
Please input password:
current has 1 threads
current has 3 threads
current has 4 threads
current has 6 threads
current has 8 threads
current has 11 threads
current has 12 threads
current has 14 threads
hello world
172.***.***.*** OK
hello world
172.***.***.*** OK
hello world
172.***.***.*** OK
hello world
172.***.***.*** OK
hello world
172.***.***.*** OK
hello world
172.***.***.*** OK
hello world
172.***.***.*** OK
hello world
172.***.***.*** OK
『叄』 python線程用什麼模塊好
在Python中可使用的多線程模塊主要有兩個,thread和threading模塊。thread模塊提供了基本的線程和鎖的支持,建議新手不要使用。threading模塊允許創建和管理線程,提供了更多的同步原語。
thread模塊函數:
start_new_thread(function, args[, kwargs]):啟動新的線程以執行function,返回線程標識。
allocate_lock():返回LockType對象。
exit():拋出SystemExit異常,如果沒有被捕獲,線程靜默退出。
LockType類型鎖對象的方法:
acquire([waitflag]):無參數,無條件獲得鎖,如果鎖已經被其他線程獲取,則等待鎖被釋放。如果使用整型參數,參數為0,如果鎖可獲取,則獲取且返回True,否則返回False;參數為非0,與無參數相同。
locked():返回鎖的狀態,如果已經被獲取,則返回True,否則返回False。
release():釋放鎖。只有已經被獲取的鎖才能被釋放,不限於同一個線程。
threading模塊提供了更好的線程間的同步機制。threading模塊下有如下對象:
Thread
Lock
RLock
Condition
Event
Semaphore
BoundedSemaphore
Timer
threading模塊內還有如下的函數:
active_count()
activeCount():返回當前alive的線程數量
Condition():返回新的條件變數對象
current_thread()
currentThread():返回當前線程對象
enumerate():返回當前活動的線程,不包括已經結束和未開始的線程,包括主線程及守護線程。
settrace(func):為所有線程設置一個跟蹤函數。
setprofile(func):為所有純種設置一個profile函數。
更多Python知識請關注Python自學網