[Tutor] [tutor] Question on multithreading

Kent Johnson kent37 at tds.net
Wed Feb 27 05:17:48 CET 2008


Varsha Purohit wrote:
> Hello,
>     i have a gui program in wxpython where i am spawning two threads. 
> one for the mainloop of gui and other for some background tasks.

It is unusual to start a new thread for the GUI. Usually the GUI is run
in the main application thread.

> I have 
> to stop the background running thread once its work is done.

A thread will stop when its run() method returns, so if you want the
thread to do some work, then stop, just have the run() method terminate.

> is there any method called stop() to 
> stop the threads....

No.

> Also, i want to see if the thread is alive or not.. 
> but i donno where should i put the isAlive() method associated with the 
> thread.. i tried putting it in the code where thread does execution but 
> apparently it is not the correct place.........

You should put isAlive() in the code that cares whether the other thread
is alive...it won't be useful to put the call to isAlive() in the thread
you are testing, it will always be alive when the method is called!


> Here is the code...
> 
> class GuiScript(threading.Thread):
>     def __init__(self):
>         self.run()
>     def run(self):
>         app = wx.PySimpleApp()
>         MainWindow().Show()
>         app.MainLoop()
>            
> class RunScript(threading.Thread):
>     def run(self):
>         imFile=test()

Do you have code to instantiate and start the threads? The above only
defines two thread classes, it doesn't actually start any threads.

> and when the stop button is pressed the two threads should stop 
> executing... so i have written code like this...
> 
> def OnCloseWindow(self,event):
>         GuiScript().Stop()

This creates a GuiScript thread - by calling GuiScript() - then calls
Stop() on the thread. The thread is never started and I don't know what
Stop() is...

wxPython has a Threads.py example that might be worth studying.
Here is a threading intro:
http://www.wellho.net/solutions/python-python-threads-a-first-example.html

Kent



More information about the Tutor mailing list