Search code examples
pythonpython-curses

Why is this thread pausing when "getstr" is used in another thread? Python Curses


I have made a thread that is supposed to show the seconds passing. Unfortunately, when I use getstr from the curses module the whole script stops, including the thread. I have to use a thread lock to stop random characters being printed out because of overlapping orders.

Any suggestions on how to fix this or an alternative would be great!

In the below example window and window2 are already set-up...

lock = threaing.Lock()


def main_function():
  #starts thread
  t1 = threading.Thread(target=time_calc,args=(window2,))
  t1.start()
  #Gets user input
  while True:
    data = window1.addstr(y,x,"Type something in!")
    data = window1.getstr(y,x,5)

    lock.acquire()
    window1.erase()
    txt = "You said: "+data

    window1.addstr(y,x,txt)
    lock.release()


def time_calc(window2):
  current_count = 0

  while True:

    time += 1

    text = "Time Count: "+str(time)

    lock.acquire()
    window2.erase()

    window2.addstr(y,x,text)
    lock.release()

    time.sleep(1)

Solution

  • The problem with my code

    I figured out the problem with my code. You can't run a thread inside a thread for some reason and I originally had my main function called to be considered a thread. I guess I should have stated this in my question. Sorry

    There is probably a way to run a thread in a thread, but this did not work for me.

    My Updated Code

    lock = threading.Lock()
    
    def call_threads():
      t1 = threading.Thread(target=main_function,args=(window1,))
      t1.start()
    
      t2 = threading.Thread(target=time_calc,args=(window2,))
      t1.start()
    
    def main_function(window1):
      #Gets user input
      while True:
        data = window1.addstr(y,x,"Type something in!")
        data = window1.getstr(y,x,5)
    
        lock.acquire()
        window1.erase()
        txt = "You said: "+data
    
        window1.addstr(y,x,txt)
        lock.release()
    
    
    def time_calc(window2):
      current_count = 0
    
      while True:
    
        time += 1
    
        text = "Time Count: "+str(time)
    
        lock.acquire()
        window2.erase()
    
        window2.addstr(y,x,text)
        lock.release()
    
        time.sleep(1)
    

    If there is anything else that may have caused this error, please comment it!