【发布时间】:2018-01-10 04:40:41
【问题描述】:
我从一个带有 curses 的 python 程序开始,然后我实现了线程,它接受输入(这里是 A 和 D 按钮)并相应地更改 x。然后主块不断地在屏幕上显示 x 的值。但是,x(全局共享变量)的值是不同的。特别是,主块测量的 x 值总是落后于 inputThread 的值,但 inputThread 是完全响应的。是什么赋予了?如何让主块读取 inputThread 测量的 x 的真实值?
import time
import curses
import threading
from curses import wrapper
from time import sleep
def inputThread(stdscr):
global x
x = 0
while True:
c = stdscr.getch()
curses.flushinp()
if c == ord('a'):
x -= 1
elif c == ord('d'):
x += 1
stdscr.addstr("inputThread:" + str(x) + "\n" + "c:" + str(c))
def main(stdscr):
curses.initscr()
stdscr.clear()
t = threading.Thread(target=inputThread, args=(stdscr,))
t.setDaemon(True)
t.start()
while True:
stdscr.clear()
stdscr.addstr("\ndisplay window:" + str(x) + "\n")
time.sleep(0.05)
wrapper(main)
样本输出;在下一次按键时,无论是 A 还是 D,显示窗口都会报告 9。
【问题讨论】:
标签: python multithreading python-curses