-1
有人能告訴我在哪裏可以把鎖定在python自定義線程內?線程在自定義線程上鎖定python
import threading
lock = threading.Lock()
class WorkerThread(threading.Thread):
def __init__(self,lock):
super(WorkerThread,self).__init__()
self.lock = lock
def run(self):
self.lock.acquire()
print "Hello World"
self.lock.release()
worker = WorkerThread(lock)
錯誤回溯:
Traceback (most recent call last):
File "<buffer>", line 14, in <module>
File "<buffer>", line 11, in __init__
AssertionError: release() of un-acquire()d lock
你可以讓你的生活使用鎖作爲一個上下文管理器觸摸更容易(和安全一般情況下)。你可以用'with self.lock:'替換acquire和release,並且在獲取鎖的同時運行該塊下面的所有內容,並在塊結束時釋放它。 –