How to perform a function several times simultaneously?

Asked

Viewed 105 times

-1

What my code does:

import time

def oi():
    while True:
        print("oi")
        time.sleep(1)

oi()

Output (in 2 seconds past):

oi
oi

What I want you to do:

import time
import multiprocessing

def oi():
    while True:
        print("oi")
        time.sleep(1)

quantidadeDeProcessos = 3

multiprocess(quantidadeDeProcessos, oi())

Output (in 2 seconds past):

oi
oi
oi
oi
oi
oi

Is there any way to do that?

  • 1

    Is there any relation of this question to the How to speed up my python program? If yes, would use this to make HTTP calls in parallel?

  • No, I was just wondering if it’s possible to do that

2 answers

1

One way to do this is simply by multiplying the amount of "hi’s" by the number of processes:

from time import sleep

def oi(num_process):
    while True:
        print('oi\n' * num_process)
        sleep(1)

oi(3)

The output will look like this (in 2 seconds interval):

oi
oi
oi

oi
oi
oi
  • but this function that I said was just an example, wanted a mode that works with any kind of function

  • @x8ss, but this would work with any type of typed string. What do you really want? Examples best your question :)

0


I figured out a way using the threading module:

import threading
import time

def a():
    while True:
        print("oi")
        time.sleep(1)

numeroDeProcessos = 3

if __name__ == "__main__":
    for i in range(numeroDeProcessos):
        threading.Thread(target=a).start()

Browser other questions tagged

You are not signed in. Login or sign up in order to post.