# 多线程共享全局变量会出现资源竞争
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)
# 如果创建Thread时执行的函数,函数运行结束意味着 这个子线程结束...
def test2(num):
global g_num
for i in range(num):
g_num += 1
print("-----test2-----g_num=%d" % g_num)
def main():
# 在调用thread之前打印当前线程信息
print(threading.enumerate())
# 创建线程
t1 = threading.Thread(target=test1, args=(1000000,))
t2 = threading.Thread(target=test2, args=(1000000,))
t1.start()
t2.start()
# 等待上面两个线程结束
time.sleep(5)
print("-----in main Thread g_num=%d" % g_num)
if __name__ == '__main__':
main()
执行结果: