Home > Software engineering >  How to run two pieces of codes with waits in between at the same time in python?
How to run two pieces of codes with waits in between at the same time in python?

Time:11-23

I want to run

import time
number1 = 1
while True:
    number1 = int(number1)   1
    time.sleep(3)

And

import time
number2 = 1
while True:
    number2 = int(number2)   1
    time.sleep(20)

At the same time in python, how would I go about doing so? I'm still a beginner, please explain it in simpler terms if you can.

Sub-question: There is little of actual code and more of waiting around, would it be better to use multithreading or multiprocessing?

Sub-question2: Can I run more processes than the number of cores my cpu has in multiprocessing?

CodePudding user response:

I would recommend using concurrency. For your purpose, it will look like everything is happening "at the same time" (here is a more in depth explanation of the two: What is the difference between concurrency, parallelism and asynchronous methods?).

You could implement concurrency by doing something like the following:

def f(num, wait):
  time.sleep(wait)
  return int(num)   1
  
numbers = [1, 2]
test = [f(num, 3) for num in numbers]

Here is another example of concurrency I wrote up in typescript that you could play around with: ts example

Note: I would warn against using multithreading / parallelism, especially if you're new to python. It can cause a lot of issues, is difficult to debug / understand, and can often cause a hit to performance rather than a gain if not implemented correctly.

Note 2: If you feel comfortable creating multiple instances and running them at the same time (as you described with bat files) you could go ahead and do that, but this makes your project difficult to share.

CodePudding user response:

You can use multiprocessing.

from multiprocessing import Process
import time
def loop_3():
    number1 = 1
    while True:
        number1 = int(number1)   1
        time.sleep(3)
        print(number1)

def loop_20():
    number2 = 1
    while True:
        number2 = int(number2)   1
        time.sleep(20)
        print(number2)


Process(target=loop_3).start()
Process(target=loop_20).start()
  • Related