很多初学多线程编程的同学肯定都会遇到多线程教程中提到的一个问题,就是共享变量在多个线程中的同步问题。
典型的例子如下:有A、B两个线程,data为共享变量。如果在B打印data的时候,A去修改了data的数值,则会造成线程之间的变量不同步。那么,需要在操作共享变量的时候,加上线程锁,从而保证数据的同步。
初学者在学习的过程中复现这个场景并不是很容易,大牛请忽略本篇文章。
所以,我将字符串作为需要同步的变量,将逐个字符的修改作为两个线程竞争的条件,复现这个场景,希望可以为初学者提供一些参考。
import threading
import time
class myThread1(threading.Thread):
def __init__(self, threadId, name):
threading.Thread.__init__(self)
self.threadID = threadId
self.name = name
def run(self):
global data
print("开始线程:{}".format(self.name))
idx = 0
# 线程锁,可注释掉做对比
threadLock.acquire()
while idx < len(data):
dataList = list(data)
dataList[idx] = '1'
data = "".join(dataList)
idx += 1
time.sleep(1)
threadLock.release()
print("退出线程:{}".format(self.name))
class myThread2(threading.Thread):
def __init__(self, threadId, name):
threading.Thread.__init__(self)
self.threadID = threadId
self.name = name
def run(self):
print("开始线程:{}".format(self.name))
# 线程锁,可注释掉做对比
threadLock.acquire()
idx = 0
while idx < 10:
print("{}-{}".format(self.name, data))
idx += 1
time.sleep(1)
threadLock.release()
print("退出线程:{}".format(self.name))
threadLock = threading.Lock()
data = '00000'
if __name__ == "__main__":
thread1 = myThread1(1, "thread1")
thread2 = myThread2(2, "thread2")
thread1.start()
thread2.start()
thread1.join()
thread2.join()
print("main func exit")
左图为加线程锁 | 右图为无线程锁 , 以此做对比, 学习还是应该多实践,希望各位可以提供更好的示例程序作为学习分享。
加线程锁 不加线程锁