一、什么是进程、线程
注意事项:
总结:
二、什么是并行执行
总结:
三、多线程编程
1、threading 模块
需求:
代码演示1:在单线程的情况下,由于程序运行的顺序性,无法执行dance()
运行结果:
代码演示2:创建2个线程,可以实现需求
import time import threading def sing(): while True: print("我在唱歌,啦啦啦···") time.sleep(1) def dance(): while True: print("我在跳舞,呱呱呱···") time.sleep(1) if __name__ == '__main__': sing_thread=threading.Thread(target=sing) dance_thread=threading.Thread(target=dance) sing_thread.start() dance_thread.start()
运行结果:
代码演示3:通过args、kwargs传参
import time import threading def sing(msg): while True: print(msg) time.sleep(1) def dance(msg): while True: print(msg) time.sleep(1) if __name__ == '__main__': sing_thread=threading.Thread(target=sing,args=("我要唱歌,哈哈哈···",)) dance_thread=threading.Thread(target=dance,kwargs={"msg":"我要跳舞,啦啦啦···"}) sing_thread.start() dance_thread.start()
运行结果: