锁是什么?什么场合使用锁?
锁是一种机制,用于保护那些会引起冲突的资源。
比如上厕所,进去之后第一件事干嘛?把厕所门反锁!表示什么呢?表示这个厕所正在使用中!
至于在厕所里面干大事、干小事、还是打飞机,都可以!
完事之后干嘛?把厕所门打开!表示什么呢?那谁,你可以进来打飞机了。
一、全局锁、函数内部上锁/解锁、函数打包进线程
import threading
import time
def my_func(num):
global counter, mutex
# 获得线程名
threadname =
threading.currentThread().getName()
for i
in range(num):
mutex.acquire() # 锁住①
counter = counter + 1
# 保护② 如同厕所坑位是抢占性资源,同一时间只能一个人去蹲
mutex.release()
# 解锁③
print(threadname, i, counter)
# 再回去,坑位counter可能已被其它人蹲过
time.sleep(1
)
if __name__ ==
'__main__':
counter = 0
# 计数器
mutex = threading.Lock()
# 创建锁
threads =
[]
for i
in range(4
):
threads.append(threading.Thread(target=my_func, args=(10,)))
# 创建线程
for t
in threads:
t.setDaemon(True) # 守护
t.start()
# 启动线程
for t
in threads:
t.join() # 阻塞主程,直到线程退出
运行效果图:
可以发现到 counter 并不是顺序显示的,看官可以思考其原因。
二、全局锁、线程类、线程类run方法中上锁/解锁
import threading
import time
class Worker(threading.Thread):
'''线程类'''
def __init__(self, num=5
):
super().__init__()
self.num =
num
def run(self):
global counter, mutex
threadname =
threading.currentThread().getName()
for i
in range(self.num):
mutex.acquire() # 锁住①
counter = counter + 1
# 保护② 如同厕所坑位是抢占性资源,同一时间只能一个人去蹲
mutex.release()
# 解锁③
print(threadname, i, counter)
# 此时,counter可能又已被其它线程改变
time.sleep(1
)
if __name__ ==
'__main__':
# 全局计数器
counter = 1
# 创建锁
mutex =
threading.Lock()
# 创建线程对象
threads =
[]
for i
in range(4
):
threads.append(Worker(10))
# 添加 4 个 Worker
# 启动线程
for t
in threads:
t.start()
# 阻塞主程
for t
in threads:
t.join()
转载于:https://www.cnblogs.com/hhh5460/p/5178157.html