其他分享
首页 > 其他分享> > 【多任务线程高级day05】多线程-共享全局变量+列表当做实参传递到线程中

【多任务线程高级day05】多线程-共享全局变量+列表当做实参传递到线程中

作者:互联网

多线程-共享全局变量

from threading import Thread
import time

g_num = 100

def work1():
    global g_num
    for i in range(3):
        g_num += 1

    print("----in work1, g_num is %d---"%g_num)


def work2():
    global g_num
    print("----in work2, g_num is %d---"%g_num)


print("---线程创建之前g_num is %d---"%g_num)

t1 = Thread(target=work1)
t1.start()

#延时一会,保证t1线程中的事情做完
time.sleep(1)

t2 = Thread(target=work2)
t2.start()

运行结果:

---线程创建之前g_num is 100---
----in work1, g_num is 103---
----in work2, g_num is 103---

列表当做实参传递到线程中

from threading import Thread
import time

def work1(nums):
    nums.append(44)
    print("----in work1---",nums)


def work2(nums):
    #延时一会,保证t1线程中的事情做完
    time.sleep(1)
    print("----in work2---",nums)

g_nums = [11,22,33]

t1 = Thread(target=work1, args=(g_nums,))
t1.start()

t2 = Thread(target=work2, args=(g_nums,))
t2.start()

运行结果:

----in work1--- [11, 22, 33, 44]
----in work2--- [11, 22, 33, 44]

总结:

汪雯琦 发布了100 篇原创文章 · 获赞 19 · 访问量 3539 私信 关注

标签:Thread,nums,day05,num,线程,work1,work2,多线程
来源: https://blog.csdn.net/qq_35456045/article/details/104071987