[python] How to execute two or more processes at the same time (threading)

Threading

Threads allow multiple functions to run simultaneously.

It can be used to improve efficiency when used for processes that require waiting time, such as scraping.

For more information → Python Documentation contents

import time
import threading


def func_1():
    for _ in Range(10):
        print("func1 start")
        time.sleep(1)


def func_2():
    for _ in Range(10):
        print("func2 start")
        time.sleep(1)


if __name__ == "__main__":
    thread_1 = threading.Thread(target=func_1)
    thread_2 = threading.Thread(target=func_2)

    thread_1.start()
    thread_2.start()

Points to note are

threading.Thread(target=func_1())

Do not do it this way. This cannot be done at the same time.

If you want to set arguments for an object, use

thread_1 = threading.Thread(target=func_1,args=(a,b))
thread_1.start()

Do it this way.

python

Posted by Next-k