0
votes

Some of my methods involve os.chdir. When used in multi threads, the chdir will impact each other.

So I tried multiprocess.Pool to call these methods in different process and it worked. Until I call these methods in GUI.

When using multiprocessing.Pool in wxPython, the method called with apply_async still freezes the GUI, how to solve this?

class MyFrame(wx.Frame):

    def __init__(self):
        super(MyFrame, self).__init__(None, -1, 'My Frame', size=(500, 300))
        self.pool = multiprocessing.Pool(maxtasksperchild=1)
        panel = wx.Panel(self, -1)
        self.screen = wx.TextCtrl(panel, -1, '', size=(500, 200), style=wx.TE_MULTILINE | wx.TE_READONLY)
        vbox = wx.BoxSizer(wx.VERTICAL)
        vbox.Add(self.screen, flag=wx.EXPAND)
        vbox.Add(wx.Button(panel, 1, label='Block'), flag=wx.BOTTOM)
        vbox.Add(wx.Button(panel, 2, label='Non-Block'), flag=wx.BOTTOM)
        panel.SetSizer(vbox)

        self.Bind(wx.EVT_BUTTON, self.onBlock, id=1)
        self.Bind(wx.EVT_BUTTON, self.onNonBlock, id=2)

    def onNonBlock(self, event):
        self.pool.apply_async(self.long_job(4))

    def onBlock(self, event):
        self.long_job(4)

    def callback(self, x):
        self.screen.WriteText('callback %s\n' % x)

    def long_job(self, x):
        self.screen.WriteText('enter %s\n' % x)
        for i in range(x):
            self.screen.WriteText('running %s\n' % i)
            os.chdir('dir_%s' % x)
            time.sleep(1)
        self.screen.WriteText('exit %s\n' % x)
1
How are you going with this? Did my answer, below, help? - GreenAsJade

1 Answers

0
votes

Your GUI is freezing because you are not giving the application processing time to redraw the graphical elements.

To correct this, you need to provide wx with this opportunity. One way to do that is to call wx.Yield() in the long_job:

def long_job(self, x):
    self.screen.WriteText('enter %s\n' % x)
    for i in range(x):
        self.screen.WriteText('running %s\n' % i)
        os.chdir('dir_%s' % x)
        wx.Yield()   ### Allow graphical processing before sleeping
        time.sleep(1)     
    self.screen.WriteText('exit %s\n' % x)