Home > Article > Backend Development > Two implementation methods of python multithreading (code tutorial)
This article brings you two implementation methods (code tutorials) of Python multi-threading. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.
Threads are lightweight processes. Multiple threads can be divided into the process, and the threads can be scheduled and run independently (instances divided in the process can run independently). For example: our computer CPU can run at the same time. Qq and WeChat, multiple chat boxes can be opened at the same time when qq is running. In the above example of qq WeChat and process, each chat box is a different thread
First type:
Use Thread in threading Method implementation
import threadingimport timedef eat(): # 循环打印,延迟一秒 while True: print("我在吃饭") time.sleep(1)def drink(): while True: print("我在喝水") time.sleep(1)def main(): thr1 = threading.Thread(target=eat) thr2 = threading.Thread(target=drink) # 创建并执行线程 thr1.start() thr2.start()if __name__ == '__main__': main()
**Second:
Use the Timer function in threading**
import timeimport threadingdef eat(): # 循环打印 while True: print("我在吃饭") # 延迟一秒 time.sleep(1)def drink(): while True: print("我在喝水") time.sleep(1)# 创建延迟触发,第一个参数为设置几秒后开始,第二个是执行函数名thr1 = threading.Timer(1, eat) thr2 = threading.Timer(1, drink) thr1.start() thr2.start()
The above are all the two ways to implement python multi-threading (code tutorial) Introduction, if you want to know more about Python video tutorial, please pay attention to the PHP Chinese website.
The above is the detailed content of Two implementation methods of python multithreading (code tutorial). For more information, please follow other related articles on the PHP Chinese website!