Two implementation methods of python multithreading (code tutorial)

云罗郡主
Release: 2018-10-20 16:09:58
forward
2792 people have browsed it

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()
Copy after login

**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()
Copy after login

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!

source:csdn.net
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template