9. 线程间通信
(1) 互斥锁
互斥锁为资源引入一个状态:锁定/非锁定。某个线程要更改共享数据时,先将其锁定,此时资源的状态为“锁定”,其他线程不能更改;直到该线程释放资源,将资源的状态变成“非锁定”,其他的线程才能再次锁定该资源。互斥锁保证了每次只有一个线程进行写入操作,从而保证了多线程情况下数据的正确性。
"""
#创建锁
mutex = threading.Lock()
#锁定
mutex.acquire([timeout])
#释放
mutex.release()
"""
import threading
money = 0
def order(n):
global money
money = money + n
money = money - n
class MyThread(threading.Thread):
def __init__(self, thread_name):
threading.Thread.__init__(self, name='线程' + thread_name)
self.thread_name = int(thread_name)
def run(self):
for i in range(1000000):
lock.acquire() # 加锁
order(self.thread_name)
lock.release() # 释放
if __name__ == '__main__':
lock = threading.Lock()
t1 = MyThread('1')
t2 = MyThread('10')
t1.start()
t2.start()
t1.join()
t2.join()
print(money)
# 结果
'''
0
'''
为了支持在同一线程中多次请求同一资源,python提供了“可重入锁”:threading.RLock。RLock内部维护着一个Lock和一个counter变量,counter记录了acquire的次数,从而使得资源可以被多次acquire。直到一个线程所有的acquire都被release,其他的线程才能获得资源。acquire() 和 release() 必须成对出现,也就是说加了几把锁就得释放几把锁。
import threading
import time
num = 0
mutex = threading.RLock()
class MyThread(threading.Thread):
def run(self