【发布时间】:2018-10-12 13:39:47
【问题描述】:
我编写了一个非常简单的程序,它有多个线程,应该打印到终端。一个线程打印出一个由 10 颗星组成的数组,另一个线程应该在后台运行,等待检测任何键盘按下。我无法解决的是,如果第二个线程正在运行,则终端中的输出无法正确打印出来。如果第二个线程停止,那么输出就是我们想要的。
完整代码(根据要求):
#ASCII Frogger
from random import randint
import time
import sys, termios, tty, os
import threading
def getch():
fd = sys.stdin.fileno()
old_settings = termios.tcgetattr(fd)
try:
tty.setraw(sys.stdin.fileno())
ch = sys.stdin.read(1)
finally:
termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)
return ch
def resetPositions():
pos = ["*", "*", "*", "*", "*", "*", "*", "*", "*", "*"]
return pos
def threadKeyPressDetection():
button_delay = 0.2
while True:
char = getch();
if (char == "p"):
#print("Stop!")
exit(0)
def threadGame():
positions = ["*", "*", "*", "*", "*", "*", "*", "*", "*", "*"]
startingPos = randint(0, 9)
frogPosition = startingPos
i = 0
ii = 0
while i < 10:
# if player press left go down in grid if space
# if player press right go up in grid if space
while ii < 10:
if i < 5:
positions[4] = (5 - i)
print positions[ii],
ii += 1
ii = 0
if i == 5:
print "\n\n\n GO "
print "\n"
positions = resetPositions()
if i > 5:
positions[frogPosition] = '!'
i += 1
time.sleep(1)
try:
t1 = threading.Thread(target=threadKeyPressDetection)
t2 = threading.Thread(target=threadGame)
t1.start()
t2.start()
t1.join()
t2.join()
except:
print("Error occured - unable to start thread")
期望的输出:
* * * * 3 * * * * *
* * * * 2 * * * * *
* * * * 1 * * * * *
GO
* * * * * * * * * *
* * * * * * ! * * *
当前输出:
* * * * 5 * * * * *
* * * * 4 * * * * *
* * * * 3 * * * * *
* * * * 2 * * * * *
* * * * 1 * * * * *
* * * * * * * * * *
GO
【问题讨论】:
-
这是一个似乎没有意义的问题,因为其他线程不应该打印到终端?
-
@Biscuit 你能添加重现这种奇怪打印所需的所有代码吗?
-
@Ralf 添加了所有代码!
标签: python