Stopping a thread from the calling process
P.J.W.S. Vrijlandt
P.J.W.S.VRIJLANDT at INT.azg.nl
Mon Jan 17 05:11:03 EST 2000
Gordon wrote:
> Scott Barron asks:
>
> > is there an easy and fairly portable way of doing this?
>
> If you mean "interrupting" or "killing", no. WIth good reason.
> OS level threads are often "light weight" processes. Generally
> what's been trimmed is all the stuff dealing with reclaming
> resources, releasing locks etc. on thread death. So if you
> "kill" a thread, you're likely to be leaving your process in an
> indeterminate state.
>
> The normal idiom is to ask politely - have the thread
> periodically check some variable to see if it should stop.
How would you do this if the thread-to-be-stopped is waiting for
(keyboard-) input?
e.g. in telnetlib we have:
def mt_interact(self):
"""Multithreaded version of interact()."""
import thread
thread.start_new_thread(self.listener, ())
while 1:
line = sys.stdin.readline()
if not line:
break
self.write(line)
def listener(self):
"""Helper for mt_interact() -- this executes in the other
thread."""
while 1:
try:
data = self.read_eager()
except EOFError:
print '*** Connection closed by remote host ***'
return
if data:
sys.stdout.write(data)
else:
sys.stdout.flush()
mt_interact should break out of its loop when EOFError occurs within
listener.
(also note that select on input won't work on win32, and looping on
keypressed seems rather processor-unfriendly)
BTW: Would this be better rewritten (for this reason or another)
using threading?
Patrick
Met vriendelijke groet,
Patrick Vrijlandt
More information about the Python-list
mailing list