Search code examples
pythonpython-3.xmultithreadingpython-multithreading

I try to do a threading system in Python but I can't


I'm trying to make a threading system that continuously runs a while cycle but at the same time performs another function that is waiting for a string.

For example, a while cycle to write "Hello World" and a function waiting for something to be typed.

So i try with this code but it's not worked :(

import threading
from time import sleep
import time

data = []

def get_input():
    data.append(input()) # Something akin to this
    return data



input_thread = threading.Thread(target=get_input)
input_thread.start()


while (True):
        print ("Hello World")
        time.sleep(1)

input_thread.join()

if data.pop=="a":
    print ("This message will be writed, only when user typed something")

Solution

  • A few things.

    • Check the array length before popping
    • The input thread must have a loop also
    • You need to press enter when you input a string

    Here is the updated code:

    import threading
    from time import sleep
    import time
    
    data = []
    
    def get_input():
        while True:
            data.append(input()) # must press enter to submit
    
    input_thread = threading.Thread(target=get_input)
    input_thread.start()
    
    while (True):
        print ("Hello World")
        time.sleep(1)
        if (len(data) and data.pop()=="a"):
            print ("This message will be writed, only when user typed something")
                
    input_thread.join()  # never gets here