适合零基础学习的—关于多任务-线程的简单练习:
import threading
import time
# 定义一个全局变量
g_num = 0
mutex = threading.Lock() # 定义一个锁
def test1(num):
global g_num
for i in range(num):
mutex.acquire() # 上锁
g_num += 1
mutex.release() # 解锁
print("-----in test1 g_num = %d" % g_num)
# g_num +=1在真正的执行的时候会解析成很多句话
# 例如:(1)获取g_num的值 (2)把获取的值 +1 (3)把第2步的结果存储到g_num中
def test2(num):
global g_num
for i in range(num):
mutex.acquire() # 上锁
g_num += 1
mutex.release() # 解锁
print("-----in test1 g_num = %d" % g_num)
def main():
t1 = threading.Thread(target=test1,args=(1000000,))
t2 = threading.Thread(target=test2,args=(1000000,))
t1.start()
t2.start()
# 等待上面的2个线程执行完毕
time.sleep(2)
print("-----in main Thread = %d" % g_num)
if __name__ == '__main__':
main()