from threading import * import time g_num = 0 def run(): lock.acquire() #获得同步锁的钥匙 print("当前进程%s,开始启动:%s" % (current_thread().name, time.time())) global g_num # 修改全局变量 for i in range(5000000): g_num += 1 print('线程%s,执行之后g_num的值为:%s' % (current_thread().name, g_num)) #进行计算之后线程释放同步锁钥匙 lock.release() if __name__ == '__main__': #创建同步锁 lock=Lock() threads = [] for i in range(5): t = Thread(target=run) t.start() threads.append(t) for j in threads: j.join() print('主线程结束,g_num的值为:%s' % g_num)
线程同步锁 解决数据计算混乱问题
最新推荐文章于 2024-09-10 13:01:50 发布