import threading
import time
lock = threading.Lock()
def Count(id):
global num;
while True:
if lock.acquire(): # 拿锁,使用资源,相当于C++11 mutex
if num <= 100:
print("Thread id is : %s The num is %s\n" % (id, str(num)))
num = num + 1
else:
break
lock.release()
# with lock: # 自动释放,不用手动release,相当于C++11 lock_guard类模板
# if num <= 100:
# print("Thread id is : %s The num is %s\n" % (id, str(num)))
# num = num + 1
# else:
# break
if __name__ == "__main__":
num = 1
t1 = threading.Thread(target=Count, args=('A',))
t2 = threading.Thread(target=Count, args=('B',))
t1.start()
t2.start()
time.sleep(5)
python 多线程和锁
最新推荐文章于 2024-12-01 16:26:27 发布