全局變量傳遞是否有延遲
測試內容: 開啓線程,在不同的線程中做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()
運行結果: