多线程-非共享数据

版权声明:本文为小盒子原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_35393693/article/details/84454798

对于全局变量,在多线程中要格外小心,否则容易造成数据错乱的情况发生

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()

运行结果:

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()

小总结

在多线程开发中,全局变量是多个线程都共享的数据,而局部变量等是各个线程的,是非共享的

猜你喜欢

转载自blog.csdn.net/qq_35393693/article/details/84454798