使用python多进程和curses,似乎终止一个进程干扰curses显示。
例如,在下面的代码中,为什么终止进程会阻止curses显示文本? (按a后按b)
更确切地说,不仅显示字符串“hello”,而且显示整个curses窗口。终止一个进程打破python诅咒
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()会导致问题:警告如果在关联进程使用管道或队列时使用此方法,则管道或队列负责被破坏,并可能被其他程序无法使用。同样,如果进程已经获得了锁或信号量等,那么终止它可能会导致其他进程死锁。“我不确定'睡眠'是如何实现的,但这可能是原因。 https://docs.python.org/3/library/multiprocessing.html#multiprocessing.Process.terminate – amuttsch
@amuttsch好主意,但那不是,请参阅我的编辑。 – Zil0