python系统编程(十)

本文探讨了多线程编程中非共享数据的概念及其重要性,并通过实例演示了局部变量在多线程环境中是如何避免数据混乱的问题。文章强调了在多线程环境下正确处理全局与局部变量的方法。

多线程-非共享数据

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

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

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

转载于:https://www.cnblogs.com/leecoffee/p/9037222.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值