Search code examples
pythonpython-3.xinfinite-looprunning-other-programs

How to continue a code while a loop is already running


I created a code that shows a real time clock at the beginning (works by a loop and refreshing itself in every 1 sec using \r ) But I want to run the rest of the code while the clock is ticking (continuously). But this isn't going any further while the loop is running. I think there is no need to write the code of the clock.


Solution

  • If you want to have a task running, while using another you can use multi-threading. This means you tell your processor two different tasks and it will be continued as long as you tell it to work. See here a post about multithreading and multiprocessing. You can use the thread function of python for this.

    Here a small example:

    import threading
    import time
    # Define a function for the thread
    def print_time( threadName, delay):
       count = 0
       while count < 10:
          time.sleep(delay)
          count += 1
          print ("%s: %s" % ( threadName, time.ctime(time.time()) ))
    
    def counter(threadName, number_of_counts, delay):
        count=0
        while count < number_of_counts:
            print ("%s: %s" % ( threadName, count))
            time.sleep(delay)
            count +=1
    # Create two threads as follows
    threading.Thread(target=print_time, args=("Thread-1", 1, )).start()
    threading.Thread(target=counter, args=("Thread-2", 100, 0.1,)).start()
    

    for further information check the documentation. Note that thread has been renamed to _thread in python 3