I wonder how to run multiple functions of python3 at the same time.

Asked 2 years ago, Updated 2 years ago, 18 views

Each function is called into the requests module using the open API. The execution speed seems to be too slow because the command lines are executed sequentially.

For example, let's say there are three functions.

def function 1(): r = requests.get('http://www.12345.com')

def function 2(): r = requests.get('http://www.56789.com')

def function 3(): r = requests.get('http://www.98765.com')

Given that there are these three functions, I wonder if there are ways to call them at the same time, not run them sequentially.

python

2022-09-22 19:39

3 Answers

Try the multiprocessing module. If you don't know the concept of multiprocessing, please reply.

from multiprocessing import Process


def func1():
    print("a")

def func2():
    print("b")

def func3():
    print("c")

# Create a process
p1 = Process(target=func1) #Process for Function 1
p2 = Process(target=func2) #Process for Function 1
p3 = Process(target=func3) #Process for Function 1

# Start each process with start. func2 runs even if func1 does not end.
p1.start()
p2.start()
p3.start()

# Wait for each process to end with join After p1.join(), perform p2.join()
p1.join()
p2.join()
p3.join()


2022-09-22 19:39

Think of a process as only one command at a time. For example,

func1()
func2()

When a process runs this script, it runs func2 after func1 is over.

You can think of multiprocessing as making multiple processes. There are a total of four processes in the answer.

As a person, if you have to wash the dishes/clean the room/laundry just like today, you don't do the dishes, clean the room, or go grocery shopping yourself.

I'll make a person who does the dishes I'm going to make a person who cleans my room Create a shopper.

Waiting for them to finish their work.


2022-09-22 19:39

I'm writing because I have an inquiry.

For a function with a return value, what do you do when you want to use it by storing it in a variable?


2022-09-22 19:39

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.