hbupig 2018-12-13
import threading import time g_num = 200 def test1(): global g_num for i in range(5): g_num += 1 print("--test1, g_num = %d--" % g_num) def test2(): global g_num print("--test2, g_num = %d--" % g_num) if __name__ == "__main__": print("--执行线程之前, g_num = %d--" % g_num) t1 = threading.Thread(target=test1) t1.start() # 延时一会儿,确保线程t1中的事情能做 time.sleep(1) t2 = threading.Thread(target=test2) t2.start()
运行结果:
--执行线程之前, g_num = 200-- --test1, g_num = 205-- --test2, g_num = 205--
在上面的程序中。test1函数
循环五次,每次将g_num
全局变量加一并打印g_num
的值,在test2函数
中仅仅打印g_num
的值。在t1线程中执行test1函数,在t2线程中执行test2函数,并在执行t2线程之前,延时一秒中来保证t1线程执行完毕。
import threading import time def test1(nums): nums.append(54) print("--test1, nums=", nums) g_nums = [1, 8, 9] def test2(nums): # 确保test1中执行完毕 time.sleep(1) print("--test2, nums=", nums) if __name__ == "__main__": t1 = threading.Thread(target=test1, args=(g_nums,)) t1.start() t2 = threading.Thread(target=test2, args=(g_nums,)) t2.start()
运行结果:
--test1, nums= [1, 8, 9, 54] --test2, nums= [1, 8, 9, 54]
假设两个线程t1和t2都要对全局变量g_num(默认是0)进行加1运算,t1和t2都各对g_num加10次,g_num的最终的结果应该为20。
但是由于是多线程同时操作,有可能出现下面情况:
import threading import time g_num = 0 def test1(num): global g_num for i in range(num): g_num += 1 print("--test1, g_num = %d--" % g_num) def test2(num): global g_num for i in range(num): g_num += 1 print("--test2, g_num = %d--" % g_num) if __name__ == "__main__": print("--创建线程之前, g_num = %d--" % g_num) t1 = threading.Thread(target=test1, args=(100,)) t1.start() t2 = threading.Thread(target=test2, args=(100,)) t2.start() while len(threading.enumerate()) != 1: time.sleep(1) print("最终结果为:g_num=%d" % g_num)
运行结果:
--创建线程之前, g_num = 0-- --test1, g_num = 100-- --test2, g_num = 200-- 最终结果为:g_num=200
在测试1的基础上,向test1和test2方法传入的参数的值为:9999999
运行结果:
--创建线程之前, g_num = 0-- --test1, g_num = 13554011-- --test2, g_num = 13571206-- 最终结果为:g_num=13571206
很显然,期待的结果为:9999999 + 9999999 = 19999998,而运行结果为:13571206。