Search code examples
pythonmultithreadingpython-multithreading

Run two functions parallel in While True Loop


I have made a Cookie Clicker game on Python and am trying to get two functions to run in parallel while in an infinite loop.

I need them to be in parallel, since I want one of them to add one to a variable every second and the other one to add one to another variable every ten seconds. I do this by just using time.sleep(), but if I use the same loop for both, it's just gonna run the first function, wait 1s then add one and then wait 10s and add another one.

Does anyone know a way around this?

def farm():
   time.sleep(random.choice(range(1, 3)))`
   x += 1

def automatic():
   time.sleep(random.choice(range(1, 10)))
   y += 1

while True:
   farm()
   automatic()

This is my code kinda simplified

I tried using two different threads from the threading library, but that started crashing.


Solution

  • Instead of using threading, you can move your sleep outside of each function and check in each cycle if relevant function should trigger.

    import time, random
    
    def farm():
        print("farm")
    
    def automatic():
        print("automatic")
    
    next_farm = random.choice(range(1, 3))
    next_automatic = random.choice(range(1, 10))
        
    while True:
        if next_farm > 0:
            next_farm -= 1
        else:
            farm()
            next_farm = random.choice(range(1, 3))
    
        if next_automatic > 0:
            next_automatic -= 1
        else:
            automatic()
            next_automatic = random.choice(range(1, 10))
    
        time.sleep(1)