Python線程鎖
例子:
import threading
class MyThread(threading.Thread):
def __init__(self, args):
#使用super寫法,按照父類.方法的方式直接重寫
super(MyThread, self).__init__()
self.args = args
def run(self):
print ("start MyThread {0}".format(self.args))
def worker(n):
print ("start worker{0}".format(n))
if __name__ == "__main__":
#同多進程使用方法
for i in xrange(1, 6):
#使用threading.Thread指定函數和參數,多線程執行
t1 = threading.Thread(target=worker, args=(i,))
#開始多線程執行
t1.start()
t1.join()
#重寫threading.Thread中的run方法實現多線程
for x in xrange(6, 11):
t2 = MyThread(x)
t2.start()
t2.join()
輸出:
start worker1
start worker2
start worker3
start worker4
start worker5
start MyThread 6
start MyThread 7
start MyThread 8
start MyThread 9
start MyThread 10
多線程鎖
多線程鎖的兩種寫法,詳見下面兩個例子
例子:
import threading
import time
def worker(name, lock):
#with寫法會自動獲得鎖並自動釋放鎖,與
with lock:
print ("start {0}".format(name))
time.sleep(2)
print ("end {0}".format(name))
if __name__ == "__main__":
#鎖的實例化
lock = threading.Lock()
t1 = threading.Thread(target=worker, args=("worker1", lock))
t2 = threading.Thread(target=worker, args=("worker2", lock))
t1.start()
t2.start()
print ("main end")
輸出:
start worker1
main end
end worker1
start worker2
end worker2
例子:
import threading
import time
def worker(name, lock):
#獲取線程鎖
lock.acquire()
#捕獲異常
try:
print ("start {0}".format(name))
time.sleep(2)
print ("end {0}".format(name))
except Exception as e:
raise e
finally:
#釋放線程鎖
lock.release()
if __name__ == "__main__":
#鎖的實例化
lock = threading.Lock()
t1 = threading.Thread(target=worker, args=("worker1", lock))
t2 = threading.Thread(target=worker, args=("worker2", lock))
t1.start()
t2.start()
print ("main end")
輸出:
start worker1
main end
end worker1
start worker2
end worker2
Python線程鎖