多任务全局共享变量问题

说明:

  • 函数中全局变量加global,改变内存地址的时候需加global,如果修改了全局变量的内存地址改变了,必须使用global,如果仅仅修改了原来内存空间中的数据,此时不用必须使用global
  • 数字,字符串,元组不可变,必须加global

共享全局变量

import threading
import time


g_num = 100


def test1(temp):
    global g_num
    g_num += 1
    temp.append(33)
    print("--------in test1 g_num = %d" % g_num) 
    print("--------in test1 g_nums = %s" % str(temp)) 


def test2(temp):
    print("--------in test2 g_num = %d"% g_num)
    print("--------in test2 g_nums = %s"% str(temp))


g_nums = [11,22]

def main():
    # target指定将来,这个线程去哪个函数执行
    # args指定函数执行时传递的参数
    t1 = threading.Thread(target = test1, args=(g_nums,))
    t2 = threading.Thread(target = test2, args=(g_nums,))

    t1.start()
    time.sleep(1)
    
    t2.start()
    time.sleep(1)

    print(
  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值