【问题标题】:Why is this thread pausing when "getstr" is used in another thread? Python Curses为什么在另一个线程中使用“getstr”时该线程会暂停? Python 诅咒
【发布时间】:2020-05-01 11:00:59
【问题描述】:

我创建了一个线程,应该显示经过的秒数。不幸的是,当我使用 curses 模块中的 getstr 时,整个脚本都会停止,包括线程。由于订单重叠,我必须使用线程锁来阻止随机字符被打印出来。

任何有关如何解决此问题或替代方案的建议都会很棒!

在下面的示例中,windowwindow2 已经设置好了...

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)

【问题讨论】:

    标签: python python-curses


    【解决方案1】:

    我的代码有问题

    我发现我的代码存在问题。由于某种原因,您不能在线程内运行线程,而我最初将我的 main 函数称为线程。我想我应该在我的问题中说明这一点。对不起

    可能有一种方法可以在一个线程中运行一个线程,但这对我来说工作。

    我的更新代码

    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)
    

    如果还有其他可能导致此错误的原因,请发表评论!

    【讨论】:

      猜你喜欢
      • 2012-01-24
      • 1970-01-01
      • 2018-12-21
      • 2022-07-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多