gpt4 book ai didi

python 线程崩溃

转载 作者:行者123 更新时间:2023-11-28 22:04:02 24 4
gpt4 key购买 nike

我有一个程序(延时制作器),它有两个更新 wx.StaticBitmap 的线程。 当两个线程访问wx.StaticBitmap时,它因错误而崩溃

python: xcb_io.c:221: poll_for_event: Assertion `(((long) (event_sequence) - (long) (dpy->request)) <= 0)' failed.

我尝试了 Google search寻找答案,我尝试自己解决,但我仍然无法弄明白。

重现此错误的一段简单代码 (这不是实际程序):

#!/usr/bin/env python

import wx
import time,os.path,glob,threading

class MyFrame(wx.Frame):
def __init__(self, *args, **kwds):

kwds["style"] = wx.DEFAULT_FRAME_STYLE
wx.Frame.__init__(self, *args, **kwds)
self.bitmap_1 = wx.StaticBitmap(self, -1, wx.NullBitmap)

self.__set_properties()
self.__do_layout()

wx.CallAfter(self._img)
def __set_properties(self):

self.SetTitle("frame_1")


def __do_layout(self):

sizer_1 = wx.BoxSizer(wx.VERTICAL)
sizer_1.Add(self.bitmap_1, 0, 0, 0)
self.SetSizer(sizer_1)
sizer_1.Fit(self)
self.Layout()



def _img(self):
Thread1= threading.Thread(target=self._img1)
Thread1.start()
Thread2 = threading.Thread(target=self._img2)
Thread2.start()

def _img1(self):
frames = glob.glob("/path/to/pngs/*.png")
frames.sort()
for i in range(len(frames)):
if os.path.isfile(frames[i]) and i%2 == 0:
print frames[i]
wx.Yield()
##time.sleep(0.5)
wx.CallAfter(self.bitmap_1.SetBitmap,wx.Bitmap(frames[i], wx.BITMAP_TYPE_ANY))
wx.CallAfter(self.Update)
def _img2(self):
frames = glob.glob("/path/to/pngs/*.png")
frames.sort()
for i in range(len(frames)):
if os.path.isfile(frames[i]) and i%2 == 1:
print frames[i]
wx.Yield()
##time.sleep(0.5)
wx.CallAfter(self.bitmap_1.SetBitmap,wx.Bitmap(frames[i], wx.BITMAP_TYPE_ANY))
wx.CallAfter(self.Update)

if __name__ == "__main__":
app = wx.PySimpleApp(0)
wx.InitAllImageHandlers()
frame_1 = MyFrame(None, -1, "")
app.SetTopWindow(frame_1)
frame_1.Show()
app.MainLoop()

我用 wx.PostEvent 解决了这个问题,请看我的回答。

最佳答案

避免崩溃和各种异常行为的最简单方法是确保只有主线程处理 GUI。您可以尝试通过查找和锁定关键代码块来做到这一点,但在我看来这是一场失败的游戏。使用事件更容易将处理线程与主线程同步:

while run:
self.timer_evt.wait() # wait for main thread to unblock me
self.timer_evt.clear()
<process stuff, put results in queue or shared variables>

在处理线程中,并且

def tick(self):
if run:
<update GUI from queued data or shared variables>
self.timer_evt.set() # unblock processing thread
self.root.after(ms, self.tick) # reschedule the GUI update

在主线程中。

关于 python 线程崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7801211/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com