多任务
一、线程:
使用threading模块
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
import threading from time import sleep,ctime def sing(): for i in range(3): print(11111) sleep(1) def dance(): for i in range(5): print(222) if __name__ =='__main__': t1 = threading.Thread(target=sing) t2 = threading.Thread(target=dance) t1.start() t2.start()
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
import threading from time import sleep,ctime def sing(): for i in range(3): print(11111) sleep(1) def dance(): for i in range(5): print(222) if __name__ =='__main__': t1 = threading.Thread(target=sing) t2 = threading.Thread(target=dance) t1.start() t2.start() while True: length = len(threading.enumerate()) print('当前的进程数:%d'%length) if length<=1: break sleep(0.5)
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
threading import Thread import time g_num = 100 def work1(): global g_num for i in range(3): g_num += 1 print("----in work1, g_num is %d---"%g_num) def work2(): global g_num print("----in work2, g_num is %d---"%g_num) print("---线程创建之前g_num is %d---"%g_num) t1 = Thread(target=work1) t1.start() #延时一会,保证t1线程中的事情做完 time.sleep(1) t2 = Thread(target=work2) t2.start()
互斥锁
# 创建锁 mutex = threading.Loock() # 锁定 mutex.acquire() # 释放 mutex.release()
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
import threading import time g_num = 0 def test1(): global g_num for i in range(100000000): mutex.acquire() g_num+=1 mutex.release() print('test1___%d'%g_num) def test2(): global g_num for i in range(100): g_num+=1 print('test2___%d'%g_num) mutex = threading.Lock p1 = threading.Thread(target=test1,) p1.start() p2= threading.Thread(target=test2,) p2.start()