socket.accept()
sismex01 at hebmex.com
sismex01 at hebmex.com
Mon Feb 10 19:07:16 EST 2003
> From: marco [mailto:marco.rossini at gmx.ch]
> Sent: Monday, February 10, 2003 5:44 PM
>
> very much simplified a function looks like this:
>
> def run():
> mysocket = socket.socket(blabla)
> mysocket.bind(blabla)
> mysocket.listen(1)
> while 1:
> newsocket, addr = mysocket.accept()
> # and so on...
>
> now this loop is in a thread which, once started, will
> never die. since a thread must (?) be killed at the
> end of the program i do have a problem, because the
> program just doesn't exit
> how can i stopp the .accept()?
>
> any help would be appreciated
>
> ->marco
Gweepnings Marco, I've had the same problem but not
anymore :-)
Instead of looping through a "while 1:", use a flag
object, which evaluates as true. Simple classes are
nice:
class FlagObject(object):
def __init__(self, value):
self.value = not not value
self.lock = thread.allocate_lock()
def __nonzero__(self):
self.lock.acquire()
try:
return self.value
finally:
self.lock.release()
def set(self):
self.lock.acquire()
try:
self.value = 1
finally:
self.lock.release()
def clear(self):
self.lock.acquire()
try:
self.value = None
finally:
self.lock.release()
Of course, some will say that the locking stuff is
excessive for such a small class, and maybe they're
right, but let's keep things (mildly) threadsafe.
So, you can evaluate an object's state just by
using it as a boolean expression:
def ThreadFunction(flag):
....
.... setuf stuff
....
while flag:
....
.... socket stuff
....
...
... shutdown stuff
...
In the controller thread, when you want to signal the
thread that it must exit, you change the object so that
now it evaluates as false. Remember that it must be
a reference to the same object you ran the function
with:
# Start thread.
ContinueRunning = FlagObject(1)
thread.start_new_thread(ThreadFunction, (ContinueRunning,))
# Do s'more stuff.
....
# Time to shutdown the thread.
ContinueRunning.clear()
and wait for the thread to exit. Presto!
Good luck :-)
-gustavo
pd: and no, I don't like the threading module.
Call me "primitive" ;-)
More information about the Python-list
mailing list