- 全局变量共享
from threading import *
from time import *
list1 = []
def add_data():
for i in range(3):
list1.append(i)
print('add',list1)
sleep(0.2)
def read_data():
print('read',list1)
if __name__ == '__main__':
add = Thread(target=add_data)
read = Thread(target=read_data)
add.start()
# add.join表示其他线程要等待add任务线程执行完才可以继续执行,可以理解为add任务线程获得了资源的优先权
# 如果没有join可以自己跑一下看看程序结果
add.join()
read.start()
- 共享全局变量可能造成的错误
from threading import *
num = 0
def task1():
global num
for i in range(1000000):
num += 1
print('task1',num)
def task2():
global num
for i in range(1000000):
num += 1
print('task2',num)
if __name__ == '__main__':
t1 = Thread(target=task1)
t2 = Thread(target=task2)
t1.start()
# 可以通过join将线程同步
# 没有join可以看看结果为多少
t1.join()
t2.start()