Search code examples
pythonmultithreadinguser-input

How to make a thread dependet from another in Python?


I used the following code from this post

from threading import Thread
import time
import os

answer = None

def ask():
    global start_time, answer
    start_time = time.time()
    answer = input("Enter a number:\n")
    time.sleep(0.001)
    return 0


def timing(t):
    global answer
    time_limit = t
    while True:
        time_taken = time.time() - start_time
        if answer is not None:
            print(f"You took {time_taken} seconds to enter a number.")
            time_limit += 3
            answer = None
        if time_taken > time_limit:
            print("Time's up !!! \n"
                  f"You took {time_taken} seconds.")
            os._exit(1)
        time.sleep(0.001)


t1 = Thread(target=ask)
t2 = Thread(target=timing, args=(5,))

t1.start()
t2.start()

What I'm trying to do is, if the user enters a number before 5 seconds have passed he got 3 more seconds to type another number. That repeats until the time has passed. But I don't know how to make it "recall" the function 'ask'.

I am happy for any help.


Solution

  • Maybe you can alter a logic a little bit:

    • when you enter the function ask(), calculate the final_time (which is from now on 5 seconds in the future)
    • in the thread timing() you only check if this final_time is still in future, if not you exit the script
    • if user enters the number in the interval, increase this final_time by 3 seconds:
    import datetime
    import os
    import time
    from threading import Thread
    
    
    def ask():
        global final_time
    
        final_time = datetime.datetime.now() + datetime.timedelta(seconds=5)
    
        while True:
            start_time = datetime.datetime.now()
            answer = input("Enter a number:\n")
            time_taken = (datetime.datetime.now() - start_time).seconds
    
            final_time += datetime.timedelta(seconds=3)
    
            print(f"You took {time_taken} seconds to enter a number.")
            print(
                f"You have {(final_time - datetime.datetime.now()).seconds} seconds still left."
            )
    
    
    def timing():
        while True:
            time.sleep(0.001)
    
            if final_time < datetime.datetime.now():
                print("Time's up !!!")
                os._exit(1)
    
    
    t1 = Thread(target=ask)
    t2 = Thread(target=timing)
    
    t1.start()
    t2.start()
    

    Prints (for example):

    Enter a number:
    1
    You took 0 seconds to enter a number.
    You have 7 still left.
    Enter a number:
    2
    You took 1 seconds to enter a number.
    You have 8 still left.
    Enter a number:
    1
    You took 3 seconds to enter a number.
    You have 8 still left.
    Enter a number:
    1
    You took 5 seconds to enter a number.
    You have 6 still left.
    Enter a number:
    Time's up !!!