前面已經演示了Python:使用threading模塊實現多線程編程二兩種方式起線程和Python:使用threading模塊實現多線程編程三threading.Thread類的重要函數,這兩篇文章的示例都是演示了互不相干的獨立線程,現在我們考慮這樣一個問題:假設各個線程需要訪問同一公共資源,我們的代碼該怎么寫?
代碼如下:
'''
Created on 2012-9-8
@author: walfred
@module: thread.ThreadTest3
'''
import threading
import time
counter = 0
class MyThread(threading.Thread):
def __init__(self):
threading.Thread.__init__(self)
def run(self):
global counter
time.sleep(1);
counter += 1
print "I am %s, set counter:%s" % (self.name, counter)
if __name__ == "__main__":
for i in range(0, 200):
my_thread = MyThread()
my_thread.start()
解決上面的問題,我們興許會寫出這樣的代碼,我們假設跑200個線程,但是這200個線程都會去訪問counter這個公共資源,并對該資源進行處理(counter += 1),代碼看起來就是這個樣了,但是我們看下運行結果:
代碼如下:
I am Thread-69, set counter:64
I am Thread-73, set counter:66I am Thread-74, set counter:67I am Thread-75, set counter:68I am Thread-76, set counter:69I am Thread-78, set counter:70I am Thread-77, set counter:71I am Thread-58, set counter:72I am Thread-60, set counter:73I am Thread-62, set counter:74I am Thread-66,set counter:75I am Thread-70, set counter:76I am Thread-72, set counter:77I am Thread-79, set counter:78I am Thread-71, set counter:78
打印結果我只貼了一部分,從中我們已經看出了這個全局資源(counter)被搶占的情況,問題產生的原因就是沒有控制多個線程對同一資源的訪問,對數據造成破壞,使得線程運行的結果不可預期。這種現象稱為“線程不安全”。在開發過程中我們必須要避免這種情況,那怎么避免?這就用到了我們在綜述中提到的互斥鎖了。
互斥鎖概念
Python編程中,引入了對象互斥鎖的概念,來保證共享數據操作的完整性。每個對象都對應于一個可稱為” 互斥鎖” 的標記,這個標記用來保證在任一時刻,只能有一個線程訪問該對象。在Python中我們使用threading模塊提供的Lock類。
我們對上面的程序進行整改,為此我們需要添加一個互斥鎖變量mutex = threading.Lock(),然后在爭奪資源的時候之前我們會先搶占這把鎖mutex.acquire(),對資源使用完成之后我們在釋放這把鎖mutex.release()。代碼如下:
|
新聞熱點
疑難解答