python 的多线程以及锁定
程序员文章站
2024-03-23 18:20:34
...
下面的代码主要是使用一个类对外部数据(myList)进行修改,由于两个线程同时对myList修改,在不加锁的情况下,可能导致数据被不安全修改。
读者可尝试将“开启锁”和“释放锁”注释,重运行,看效果。
#!/usr/local/bin/python
# coding: utf-8
import threading
import time
class ChangeVal(threading.Thread):
# 继承threading.Thread并初始化,相当于构造函数
def __init__(self, myList, changeType, threadLock):
threading.Thread.__init__(self)
# self.myList 会指向外部传入的myList的同一个物理地址。相当于传入了C++的引用类型。
self.myList = myList
self.changeType = changeType
self.threadLock = threadLock
# 重写run
def run(self):
# 开启锁
self.threadLock.acquire()
if self.changeType:
self.change1()
else:
self.change2()
# 释放锁
self.threadLock.release()
# 将myList数据全部改为1
def change1(self):
for i in range(len(self.myList)):
time.sleep(1)
self.myList[i] = 1
print "in change1:" + str(self.myList)
# 将myList数据全部改为2
def change2(self):
for i in range(len(self.myList)):
time.sleep(1)
self.myList[i] = 2
print "in change2:" + str(self.myList)
if __name__ == "__main__":
# 初始化用于给多个线程操作的数据
myList = [0 for i in range(10)]
# 初始化锁的对象
threadLock = threading.Lock()
thread1 = ChangeVal(myList, True, threadLock)
thread2 = ChangeVal(myList, False, threadLock)
threads = [thread1, thread2]
print "origin is:" + str(myList)
thread1.start()
thread2.start()
# 等待所有线程结束
for t in threads:
t.join()
print "all threads exit"