Nic*_*vis 24 python queue multithreading pygame numpy
我和我的朋友一直致力于一个大型项目,以便在python和PyGame中学习和娱乐.基本上它是一个小村庄的AI模拟.我们想要一个日/夜循环,所以我找到了一种利用numpy改变整个表面颜色的巧妙方法(特别是交叉渐变教程) - http://www.pygame.org/docs/tut/surfarray/SurfarrayIntro. HTML
我将它实现到代码中并且工作正常,但速度非常慢,比如<1 fps slow.所以我看看线程(因为我想最终添加它)并在队列中找到这个页面 - 在python中学习队列模块(如何运行它)
我花了大约15分钟制作一个基本系统,但是一旦我运行它,窗口关闭,它说
Exception in thread Thread-1 (most likely raised during interpreter shutdown):
Run Code Online (Sandbox Code Playgroud)
编辑:这就是它所说的全部,没有回溯错误
我不知道我做错了什么,但我想我错过了一些简单的事情.我在下面添加了代码的必要部分.
q_in = Queue.Queue(maxsize=0)
q_out = Queue.Queue(maxsize=0)
def run(): #Here is where the main stuff happens
#There is more here I am just showing the essential parts
while True:
a = abs(abs(world.degree-180)-180)/400.
#Process world
world.process(time_passed_seconds)
blank_surface = pygame.Surface(SCREEN_SIZE)
world.render(blank_surface) #The world class renders everything onto a blank surface
q_in.put((blank_surface, a))
screen.blit(q_out.get(), (0,0))
def DayNight():
while True:
blank_surface, a = q_in.get()
imgarray = surfarray.array3d(blank_surface) # Here is where the new numpy stuff starts (AKA Day/Night cycle)
src = N.array(imgarray)
dest = N.zeros(imgarray.shape)
dest[:] = 20, 30, 120
diff = (dest - src) * a
xfade = src + diff.astype(N.int)
surfarray.blit_array(blank_surface, xfade)
q_out.put(blank_surface)
q_in.task_done()
def main():
MainT = threading.Thread(target=run)
MainT.daemon = True
MainT.start()
DN = threading.Thread(target=DayNight)
DN.daemon = True
DN.start()
q_in.join()
q_out.join()
Run Code Online (Sandbox Code Playgroud)
如果有人可以提供帮助,将不胜感激.谢谢.
Tim*_*ers 50
这在使用守护程序线程时非常常见.你为什么要设置.daemon = True线程?想一想.虽然守护程序线程有合法用途,但大多数情况下程序员都会这样做,因为他们感到困惑,因为"我不知道如何干净地关闭我的线程,如果不这样做,程序会在退出时冻结,所以我知道!我会说他们是守护线程.然后解释器不会等待它们退出时终止.问题解决了."
但它没有解决 - 它通常只会产生其他问题.特别是,守护程序线程继续运行,而解释器在 - 退出时 - 自行销毁.模块被破坏,stdin和stdout以及stderr被破坏等等.然后,守护程序线程中出现各种各样的东西,因为它们试图访问的东西被湮灭了.
在某些线程中引发异常时会产生您看到的特定消息,但到目前为止,解释器破坏已经到达,即使sys模块也不再包含任何可用的内容.线程实现保留了对sys.stderr内部的引用,以便它可以告诉你某些东西(具体来说,你正在看到的确切消息),但是过多的解释器已被销毁,告诉你其他任何关于出错的地方.
因此,找到一种方法来干净地关闭你的线程(并删除.daemon = True).对你的问题了解不够,建议一个具体的方法,但你会想到一些事情;-)
顺便说一句,我建议删除maxsize=0你的Queue()构造函数的参数.默认是"无限制","每个人都知道",而很少有人知道这maxsize=0也意味着"无限制".这种情况变得更糟,因为其他数据类型的maxsize=0意思是"最大尺寸确实是0"(最好的例子是collections.deque); 但"没有争论意味着无限制"仍然普遍存在.