import threading
g_num = 0
def test(n):
global g_num
for x in range(n):
g_num += x
g_num -= x
print(g_num)
if __name__ == '__main__':
t1 = threading.Thread(target=test, args=(10,))
t2 = threading.Thread(target=test, args=(10,))
t1.start()
t2.start()
在一个进程内的所有线程共享全局变量,很方便在多个线程间共享数据。缺点就是,线程是对全局变量随意遂改可能造成多线程之间对全局变量的混乱(即线程非安全)。
import threading
import time
ticket = 20
def sell_ticket():
global ticket
while True:
if ticket > 0:
time.sleep(0.5)
ticket -= 1
print('{}卖了一张票,还剩{}'.format(threading.current_thread().name, ticket))
else:
print('{}票卖完了'.format(threading.current_thread().name))
break
for i in range(5):
t = threading.Thread(target=sell_ticket, name='thread-{}'.format(i + 1))
t.start()