企业🤖AI Agent构建引擎,智能编排和调试,一键部署,支持私有化部署方案 广告
#### 多线程-非共享数据 对于全局变量,在多线程中要格外小心,否则容易造成数据错乱的情况发生 ##### 1. 非全局变量是否要加锁呢? ~~~ #coding=utf-8 import threading import time class MyThread(threading.Thread): # 重写 构造方法 def __init__(self,num,sleepTime): threading.Thread.__init__(self) self.num = num self.sleepTime = sleepTime def run(self): self.num += 1 time.sleep(self.sleepTime) print('线程(%s),num=%d'%(self.name, self.num)) if __name__ == '__main__': mutex = threading.Lock() t1 = MyThread(100,5) t1.start() t2 = MyThread(200,1) t2.start() ~~~ 运行结果: ![](https://box.kancloud.cn/2c1535789b9caa7347caffdedd189cbe_715x140.gif) ~~~ import threading from time import sleep def test(sleepTime): num=1 sleep(sleepTime) num+=1 print('---(%s)--num=%d'%(threading.current_thread(), num)) t1 = threading.Thread(target = test,args=(5,)) t2 = threading.Thread(target = test,args=(1,)) t1.start() t2.start() ~~~ 运行结果: ![](https://box.kancloud.cn/baceab60af19b2cf6964415de76dc05a_722x157.gif) >[warning] 小总结 * 在多线程开发中,全局变量是多个线程都共享的数据,而局部变量等是各自线程的,是非共享的