【发布时间】:2023-03-26 07:28:01
【问题描述】:
使用 python 多处理和curses,终止进程似乎会干扰curses显示。
例如,在下面的代码中,为什么终止进程会阻止 curses 显示文本? (按a后按b)
更准确地说,似乎不仅字符串“hello”不再显示,而且整个curses窗口也不再显示。
import curses
from multiprocessing import Process
from time import sleep
def display(stdscr):
stdscr.clear()
curses.newwin(0,0)
stdscr.timeout(500)
p = None
while True:
stdscr.addstr(1, 1, "hello")
stdscr.refresh()
key = stdscr.getch()
if key == ord('a') and not p:
p = Process(target = hang)
p.start()
elif key == ord('b') and p:
p.terminate()
def hang():
sleep(100)
if __name__ == '__main__':
curses.wrapper(display)
我在 GNU/Linux 下运行 python 3.6。
编辑:
我仍然能够使用这个不调用 sleep() 的更精简的版本进行复制。现在只需按“a”即可触发错误。
import curses
from multiprocessing import Process
def display(stdscr):
stdscr.clear()
curses.newwin(0,0)
stdscr.timeout(500)
p = None
while True:
stdscr.addstr(1, 1, "hello")
stdscr.refresh()
key = stdscr.getch()
if key == ord('a') and not p:
p = Process(target = hang)
p.start()
p.terminate()
def hang():
while True:
temp = 1 + 1
if __name__ == '__main__':
curses.wrapper(display)
【问题讨论】:
-
根据文档,当进程使用锁或信号量时,使用
terminate()可能会导致问题:Warning If this method is used when the associated process is using a pipe or queue then the pipe or queue is liable to become corrupted and may become unusable by other process. Similarly, if the process has acquired a lock or semaphore etc. then terminating it is liable to cause other processes to deadlock.我不确定sleep是如何实现的,但这可能是原因. docs.python.org/3/library/… -
@amuttsch 好主意,但不是这样,请参阅我的编辑。
标签: python python-multiprocessing python-curses