473,587 Members | 2,463 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Threading module question

I've written a Tkinter application (Windows) that uses the threading
module, which I've reduced to the test case below (apologies if it's a
bit long). Using the Queue module to pass messages the callable
function in ClassDoRun can be started and interrupted via 'Start' and
'Abort' buttons. Having started then interrupted the function I
expected to be able to execute the function again from the beginning
using the 'Start' button - but I get an error message saying that the
thread is already running, even though the function has been exited.
How do I fix this?

Andrew.

# threaddemo.py
#
# Python 2.3.4 (requires Tix)
#
import threading, Queue, Tix, time

# In the full program the function below
# controls various instruments and collects data.
# A much-shortened version is given here.
class ClassDoRun:

def __init__(self, CS):
self.CS = CS

def __call__(self):
CS = self.CS
for i in range(10):
CS.Counter.set( i) # write a value for display in GUI
time.sleep(1.0)
if CS.AbortRun: break

class CommonStuff: # to provide two-way common access to variables
# and functions by GUI and 'run' threads
def __init__(self, root):
self.root=root
self.root.title ("threaddemo.py , vs 12-Jul-2004")
self.frame = Tix.Frame(root)
self.frame.bind ("<Destroy>",se lf.CleanUp)
self.AbortRun=0
self.Counter=Ti x.IntVar()

def myquit(self):
self.root.destr oy()

def CleanUp(self, event):
print "Cleaning up after Tkinter closed"

def ButtonBoxWidget (Fquit, Frun, Fabort, frame):
butbox = Tix.ButtonBox(f rame, orientation=Tix .HORIZONTAL)
butbox.add('sta rt', text='Start', underline=0, width=6,
command=Frun)
butbox.add('abo rt', text='Abort', underline=0, width=6,
command=Fabort)
butbox.add('qui t', text='Quit', underline=0, width=6,
command=Fquit)
return butbox

class MainWidget(Comm onStuff, Tix.TixWidget):
def __init__(self, CS, Qput):
self.CS = CS
self.Qput = Qput
self.Lcounter = Tix.Label(CS.fr ame, textvariable=CS .Counter)
self.Lcounter.g rid(row=0, column=0, pady=5)
self.butbox = ButtonBoxWidget (CS.myquit, self.SendRunMes sage,
self.SendAbortM essage, CS.frame)
self.butbox.gri d(row=1, column=0)

def SendRunMessage( self):
self.Qput('run' )

def SendAbortMessag e(self):
self.Qput('abor t')
class Application:
def __init__(self, CS):
self.CS = CS
self.Q = Queue.Queue() # Pass messages to separate run
# thread via the queue Q
self.displayedw idget=MainWidge t(CS, self.Q.put)
CS.frame.pack()
self.RunnableOb ject = ClassDoRun(CS)
self.thread = threading.Threa d(target=self.R unnableObject)
self.poll()

def MessageQueue(se lf): # messages e.g. Run, Abort
self.CS.root.up date()
while self.Q.qsize():
try:
msg = self.Q.get(0)
if msg=="abort": self.CS.AbortRu n = 1
if msg=="run":
self.CS.AbortRu n=0
if not self.thread.isA live(): self.thread.sta rt()
except Queue.Empty: pass

def poll(self):
#print self.thread.isA live()
self.MessageQue ue()
self.CS.root.af ter(100, self.poll)
if __name__ == '__main__':
root = Tix.Tk()
CS = CommonStuff(roo t)
mainWin = Application(CS)
root.mainloop()
Jul 18 '05 #1
3 1669
On 13 Jul 2004 07:40:14 -0700, an************@ npl.co.uk (Andrew Gregory)
declaimed the following in comp.lang.pytho n:

expected to be able to execute the function again from the beginning
using the 'Start' button - but I get an error message saying that the
Read the manual...
"""
start( )

Start the thread's activity.
This must be called at most once per thread object. It arranges for the
object's run() method to be invoked in a separate thread of control.

"""

Note the clause: "... once per thread object"
thread is already running, even though the function has been exited.
How do I fix this?
As the old joke finishes: "Stop doing that"

I'd use a sequence of joining the dead thread, deleting it, and
creating a whole new thread object.

-- =============== =============== =============== =============== == <
wl*****@ix.netc om.com | Wulfraed Dennis Lee Bieber KD6MOG <
wu******@dm.net | Bestiaria Support Staff <
=============== =============== =============== =============== == <
Home Page: <http://www.dm.net/~wulfraed/> <
Overflow Page: <http://wlfraed.home.ne tcom.com/> <

Jul 18 '05 #2
Solution: You cannot re-run a threaded function, but you can delete
the thread
a create a new one. I'm sure that I should have thought of that
before, but this is the first occasion that I've tried to use use
threads, and this was not obvious to me from the docs. I've posted the
code in case it's useful to others.
I know that it could be shortened, but it is a model for a much longer
script.

General comment: Writing Tkinter and Tix GUI applications is quite
easy most of the time, quite often I find that I can just copy and
paste from something that I've written before. It only becomes tricky
when programming something that you haven't tried before. What would
really help would be a good selection of examples (PYTHONCARD is quite
good in this respect). I know there are some (e.g. in the Tix
download), but more would help. Does anyone know any good sites for
examples?

# threaddemo.py
#
# Demonstrate a Tix GUI which can launch and interrupt
# a function in a separate thread.
#
# A. P. Gregory, 15th July 2004.
#
# Python 2.3.4 (requires Tix)
#
import threading, Queue, Tix, time
import tkFont

class ClassDoRun:

def __init__(self, CS):
self.CS = CS
CS.Counter.set( 'Press to start\ncountdow n')

def __call__(self):
CS = self.CS
for i in range(0,10):
CS.Counter.set( str(10-i)+'/10') # write a value for
display in GUI
time.sleep(1.0)
if CS.AbortRun:
CS.Counter.set( 'Aborted\n(can re-start)')
return
CS.Counter.set( 'Bang!')
class CommonStuff: # to provide two-way common access to variables
# and functions by GUI and 'run' threads
def __init__(self, root):
self.root=root
self.root.title ("threaddemo.py , vs 15-Jul-2004")
self.frame = Tix.Frame(root)
self.frame.bind ("<Destroy>",se lf.CleanUp)
self.AbortRun=0
self.Counter=Ti x.StringVar()

def myquit(self):
self.root.destr oy()

def CleanUp(self, event):
print "Cleaning up after Tkinter closed"

class ButtonBoxWidget :
def __init__(self, Fquit, Frun, Fabort, frame):
butbox = Tix.ButtonBox(f rame, orientation=Tix .HORIZONTAL)
self.butbox = butbox
butbox.add('sta rt', text='Start', underline=0, width=6,
command=Frun)
butbox.add('abo rt', text='Abort', underline=0, width=6,
command=Fabort)
butbox.add('qui t', text='Quit', underline=0, width=6,
command=Fquit)
def grid(self, **kwargs): self.butbox.gri d(kwargs)

class MainWidget(Comm onStuff, Tix.TixWidget):
def __init__(self, CS, Qput):
self.CS = CS
self.Qput = Qput
self.Lcounter = Tix.Label(CS.fr ame, textvariable=CS .Counter,
font=('Sans Serif', 16, 'bold'), fg='blue', bg='white', padx=16,
height=2, width=8)
self.Lcounter.g rid(row=0, column=0, pady=15)
self.butbox = ButtonBoxWidget (CS.myquit, self.SendRunMes sage,
self.SendAbortM essage, CS.frame)
self.butbox.gri d(row=1, column=0)

def SendRunMessage( self):
self.Qput('run' )

def SendAbortMessag e(self):
self.Qput('abor t')
class Application:
def __init__(self, CS):
self.CS = CS
self.Q = Queue.Queue() # Pass messages to separate run thread
via the queue Q
self.displayedw idget=MainWidge t(CS, self.Q.put)
CS.frame.pack()
self.RunnableOb ject = ClassDoRun(CS)
self.thread = threading.Threa d(target=self.R unnableObject)
self.poll()

def MessageQueue(se lf): # messages e.g. Run, Abort
self.CS.root.up date()
while self.Q.qsize():
try:
msg = self.Q.get(0)
if msg=="abort": self.CS.AbortRu n = 1
if msg=="run":
self.CS.AbortRu n=0
if not self.thread.isA live():
del self.thread # Cannot re-run
function,
# but can delete
thread
# and run as new.
self.thread = threading.Threa d(
target=self.Run nableObject)
self.thread.sta rt()
except Queue.Empty: pass

def poll(self):
#print self.thread.isA live()
self.MessageQue ue()
self.CS.root.af ter(100, self.poll)
if __name__ == '__main__':
root = Tix.Tk()
CS = CommonStuff(roo t)
mainWin = Application(CS)
root.mainloop()
Jul 18 '05 #3
In article <28************ **************@ posting.google. com>,
Andrew Gregory <an************ @npl.co.uk> wrote:

Solution: You cannot re-run a threaded function, but you can delete
the thread a create a new one. I'm sure that I should have thought of
that before, but this is the first occasion that I've tried to use use
threads, and this was not obvious to me from the docs. I've posted the
code in case it's useful to others.


Better answer: re-use the thread. Have the thread you create sitting on
a Queue, waiting for input.
--
Aahz (aa**@pythoncra ft.com) <*> http://www.pythoncraft.com/

Barbara Boxer speaks for me:
http://buffaloreport.com/2004/040713....marriage.html
Jul 18 '05 #4

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

19
6456
by: Jane Austine | last post by:
As far as I know python's threading module models after Java's. However, I can't find something equivalent to Java's interrupt and isInterrupted methods, along with InterruptedException. "somethread.interrupt()" will wake somethread up when it's in sleeping/waiting state. Is there any way of doing this with python's thread? I suppose thread interrupt is a very primitive functionality for stopping a blocked thread.
13
2703
by: Varun | last post by:
Hi Friends, Department of Information Technology, Madras Institute of Technology, Anna University, India is conducting a technical symposium, Samhita. As a part of samhita, an Online Programming Contest is scheduled on Sunday, 27 Feb 2005. This is the first Online Programming Contest in India to support Python !!!!. Other languages supported are C and C++.
3
1489
by: David Harrison | last post by:
I am working on an application on Mac OS X that calls out to python via PyImport_ImportModule(). I find that if the imported module creates and starts a python thread, the thread seems to be killed when the import of the module is complete. Is this expected? Does python have to be in control to allow threads to run? Would it be better to arrange things such that the file is processed using PyRun_SimpleFile? David S. Harrison
6
1122
by: Matt Long | last post by:
I was wondering if any one could help me out with a threading question. Im developing an app which starts a thread, which in turn starts 4 of its own threads. If I call 'sleep' on the initial thread, will this cause all of its children to sleep also? Thanks in advance.
2
275
by: Jason MacKenzie | last post by:
I'm attempting to write data to our SAP system in VB.Net. The problem is that in certain situations, my app will hang until SAP has resources available. This causes huge problems for us the issue isn't noticed until our inventory people call in a panic. Is there a way I can use threading to throw an exception if its been hung on that line for over a minute? If this is not applicable I'm open to any suggestions.
2
1415
by: hecklar | last post by:
This is my first time posting here, so i apologize if i'm posting in the wrong subgroup or whatever, but here goes... I’m having a problem with threading and events (permissions?) in a VB.net Windows application (background service). I’m trying to write an application that processes files, launching a new thread for each file that is dropped into a certain folder. Now, the application works like a charm on my Win2000 machine, but...
4
3883
by: rh0dium | last post by:
Hi all, I have a problem with putting a job in the background. Here is my (ugly) script which I am having problems getting to background. There are threads about doing python script.py & and others
3
977
by: Sparky | last post by:
It seems strange, but I can't find a list of operating systems which support / don't support threading in Python. Can anyone point me in the right direction? Thanks, Sam
0
1215
by: Edwin.Madari | last post by:
1. check out the Caveats for thread module: http://docs.python.org/lib/module-thread.html Threads interact strangely with interrupts: the KeyboardInterrupt exceptionwill be received by an arbitrary thread. (When the signal module is available, interrupts always go to the main thread.) i.e., all threads (including main) to catch interrupt exceptions, and propagate that information to other threads. 2. since there is no way to interrupt...
0
7854
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
8219
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
8349
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
8221
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
6629
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
5722
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
3845
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
2364
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
1
1455
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.