[英]Python threading. How do I lock a thread?
我試圖了解線程和並發的基礎知識。 我想要一個簡單的案例,其中兩個線程反復嘗試訪問一個共享資源。
代碼:
import threading
class Thread(threading.Thread):
def __init__(self, t, *args):
threading.Thread.__init__(self, target=t, args=args)
self.start()
count = 0
lock = threading.Lock()
def incre():
global count
lock.acquire()
try:
count += 1
finally:
lock.release()
def bye():
while True:
incre()
def hello_there():
while True:
incre()
def main():
hello = Thread(hello_there)
goodbye = Thread(bye)
while True:
print count
if __name__ == '__main__':
main()
所以,我有兩個線程,都試圖增加計數器。 我認為如果線程 'A' 調用了incre()
,則會建立lock
,阻止 'B' 訪問,直到 'A' 釋放。
運行 清楚地表明情況並非如此。 您將獲得所有隨機數據競爭性增量。
鎖對象究竟是如何使用的?
編輯,此外,我嘗試將鎖放在線程函數中,但仍然沒有運氣。
你可以看到你的鎖在你使用它們時非常有效,如果你減慢這個過程並讓它們阻塞更多一點。 你的想法是正確的,你用鎖包圍了關鍵的代碼片段。 這是對您的示例的一個小調整,以向您展示每個人如何等待另一個人釋放鎖定。
import threading
import time
import inspect
class Thread(threading.Thread):
def __init__(self, t, *args):
threading.Thread.__init__(self, target=t, args=args)
self.start()
count = 0
lock = threading.Lock()
def incre():
global count
caller = inspect.getouterframes(inspect.currentframe())[1][3]
print "Inside %s()" % caller
print "Acquiring lock"
with lock:
print "Lock Acquired"
count += 1
time.sleep(2)
def bye():
while count < 5:
incre()
def hello_there():
while count < 5:
incre()
def main():
hello = Thread(hello_there)
goodbye = Thread(bye)
if __name__ == '__main__':
main()
示例輸出:
...
Inside hello_there()
Acquiring lock
Lock Acquired
Inside bye()
Acquiring lock
Lock Acquired
...
import threading # global variable x x = 0 def increment(): """ function to increment global variable x """ global x x += 1 def thread_task(): """ task for thread calls increment function 100000 times. """ for _ in range(100000): increment() def main_task(): global x # setting global variable x as 0 x = 0 # creating threads t1 = threading.Thread(target=thread_task) t2 = threading.Thread(target=thread_task) # start threads t1.start() t2.start() # wait until threads finish their job t1.join() t2.join() if __name__ == "__main__": for i in range(10): main_task() print("Iteration {0}: x = {1}".format(i,x))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.