全局变量传递是否有延迟

全局变量传递是否有延迟

测试内容: 开启线程,在不同的线程中做while循环,使用全局变量传递函数,测试数据是否有丢失。
测试结果: 全局变量在两个不同的def()中运行,主要是def()自身运行时间决定,如果两个def()运行时间不一致,便会出现数据丢失。

代码:

import os
import sys
import time
import threading

shu1 = 0

def test1():
    global shu1
    while 1:
        time.sleep(0.01)
        print("test1:", shu1)

def test2():
    global shu1
    while 1:
        for zz in range(10):
            shu1 = shu1 + 1
            time.sleep(0.01)
        print("test2:", shu1)

def test3():
    pass

    # global shu1
    # while 1:
    #     time.sleep(0.01)
    #     print("test3:", shu1)
if __name__ == '__main__':
    test_one = threading.Thread(target = test1)
    test_two = threading.Thread(target = test2)
    test_three = threading.Thread(target = test3)
    test_one.start()
    test_two.start()
    test_three.start()

运行结果:
在这里插入图片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章