What happens if the function of a python thread is completed? - python

I am using python thread while I found no method to stop it.
Here is how I use the thread:
class MyThread(Thread):
def __init__(self, func, args=()):
Thread.__init__(self)
self.__return_value = None
self.func = func
self.args = args
self.func_name = func.__name__
def run(self):
self.__return_value = self.func(*self.args)
Considering there is no explicit way to stop it, I try to ignore it when it finishes the function to execute.
Will a zombie thread left if I do nothing when it finishes?

No - the thread pack up after itself and shuts down cleanly.
It is how things in Python try to work, after all.
import threading
import time
def worker():
time.sleep(1)
def main():
print (threading.active_count())
t = threading.Thread(target=worker)
t.start()
print(threading.active_count())
time.sleep(2)
print(threading.active_count())
return t
main()
t = main()
t.is_alive()
Running this snippet in ipython (an interactive prompt which uses some threads for its own purposes) will print
4
5
4
False

Related

Stopping eval code dinamically on event fired [duplicate]

What's the proper way to tell a looping thread to stop looping?
I have a fairly simple program that pings a specified host in a separate threading.Thread class. In this class it sleeps 60 seconds, the runs again until the application quits.
I'd like to implement a 'Stop' button in my wx.Frame to ask the looping thread to stop. It doesn't need to end the thread right away, it can just stop looping once it wakes up.
Here is my threading class (note: I haven't implemented looping yet, but it would likely fall under the run method in PingAssets)
class PingAssets(threading.Thread):
def __init__(self, threadNum, asset, window):
threading.Thread.__init__(self)
self.threadNum = threadNum
self.window = window
self.asset = asset
def run(self):
config = controller.getConfig()
fmt = config['timefmt']
start_time = datetime.now().strftime(fmt)
try:
if onlinecheck.check_status(self.asset):
status = "online"
else:
status = "offline"
except socket.gaierror:
status = "an invalid asset tag."
msg =("{}: {} is {}. \n".format(start_time, self.asset, status))
wx.CallAfter(self.window.Logger, msg)
And in my wxPyhton Frame I have this function called from a Start button:
def CheckAsset(self, asset):
self.count += 1
thread = PingAssets(self.count, asset, self)
self.threads.append(thread)
thread.start()
Threaded stoppable function
Instead of subclassing threading.Thread, one can modify the function to allow
stopping by a flag.
We need an object, accessible to running function, to which we set the flag to stop running.
We can use threading.currentThread() object.
import threading
import time
def doit(arg):
t = threading.currentThread()
while getattr(t, "do_run", True):
print ("working on %s" % arg)
time.sleep(1)
print("Stopping as you wish.")
def main():
t = threading.Thread(target=doit, args=("task",))
t.start()
time.sleep(5)
t.do_run = False
if __name__ == "__main__":
main()
The trick is, that the running thread can have attached additional properties. The solution builds
on assumptions:
the thread has a property "do_run" with default value True
driving parent process can assign to started thread the property "do_run" to False.
Running the code, we get following output:
$ python stopthread.py
working on task
working on task
working on task
working on task
working on task
Stopping as you wish.
Pill to kill - using Event
Other alternative is to use threading.Event as function argument. It is by
default False, but external process can "set it" (to True) and function can
learn about it using wait(timeout) function.
We can wait with zero timeout, but we can also use it as the sleeping timer (used below).
def doit(stop_event, arg):
while not stop_event.wait(1):
print ("working on %s" % arg)
print("Stopping as you wish.")
def main():
pill2kill = threading.Event()
t = threading.Thread(target=doit, args=(pill2kill, "task"))
t.start()
time.sleep(5)
pill2kill.set()
t.join()
Edit: I tried this in Python 3.6. stop_event.wait() blocks the event (and so the while loop) until release. It does not return a boolean value. Using stop_event.is_set() works instead.
Stopping multiple threads with one pill
Advantage of pill to kill is better seen, if we have to stop multiple threads
at once, as one pill will work for all.
The doit will not change at all, only the main handles the threads a bit differently.
def main():
pill2kill = threading.Event()
tasks = ["task ONE", "task TWO", "task THREE"]
def thread_gen(pill2kill, tasks):
for task in tasks:
t = threading.Thread(target=doit, args=(pill2kill, task))
yield t
threads = list(thread_gen(pill2kill, tasks))
for thread in threads:
thread.start()
time.sleep(5)
pill2kill.set()
for thread in threads:
thread.join()
This has been asked before on Stack. See the following links:
Is there any way to kill a Thread in Python?
Stopping a thread after a certain amount of time
Basically you just need to set up the thread with a stop function that sets a sentinel value that the thread will check. In your case, you'll have the something in your loop check the sentinel value to see if it's changed and if it has, the loop can break and the thread can die.
I read the other questions on Stack but I was still a little confused on communicating across classes. Here is how I approached it:
I use a list to hold all my threads in the __init__ method of my wxFrame class: self.threads = []
As recommended in How to stop a looping thread in Python? I use a signal in my thread class which is set to True when initializing the threading class.
class PingAssets(threading.Thread):
def __init__(self, threadNum, asset, window):
threading.Thread.__init__(self)
self.threadNum = threadNum
self.window = window
self.asset = asset
self.signal = True
def run(self):
while self.signal:
do_stuff()
sleep()
and I can stop these threads by iterating over my threads:
def OnStop(self, e):
for t in self.threads:
t.signal = False
I had a different approach. I've sub-classed a Thread class and in the constructor I've created an Event object. Then I've written custom join() method, which first sets this event and then calls a parent's version of itself.
Here is my class, I'm using for serial port communication in wxPython app:
import wx, threading, serial, Events, Queue
class PumpThread(threading.Thread):
def __init__ (self, port, queue, parent):
super(PumpThread, self).__init__()
self.port = port
self.queue = queue
self.parent = parent
self.serial = serial.Serial()
self.serial.port = self.port
self.serial.timeout = 0.5
self.serial.baudrate = 9600
self.serial.parity = 'N'
self.stopRequest = threading.Event()
def run (self):
try:
self.serial.open()
except Exception, ex:
print ("[ERROR]\tUnable to open port {}".format(self.port))
print ("[ERROR]\t{}\n\n{}".format(ex.message, ex.traceback))
self.stopRequest.set()
else:
print ("[INFO]\tListening port {}".format(self.port))
self.serial.write("FLOW?\r")
while not self.stopRequest.isSet():
msg = ''
if not self.queue.empty():
try:
command = self.queue.get()
self.serial.write(command)
except Queue.Empty:
continue
while self.serial.inWaiting():
char = self.serial.read(1)
if '\r' in char and len(msg) > 1:
char = ''
#~ print('[DATA]\t{}'.format(msg))
event = Events.PumpDataEvent(Events.SERIALRX, wx.ID_ANY, msg)
wx.PostEvent(self.parent, event)
msg = ''
break
msg += char
self.serial.close()
def join (self, timeout=None):
self.stopRequest.set()
super(PumpThread, self).join(timeout)
def SetPort (self, serial):
self.serial = serial
def Write (self, msg):
if self.serial.is_open:
self.queue.put(msg)
else:
print("[ERROR]\tPort {} is not open!".format(self.port))
def Stop(self):
if self.isAlive():
self.join()
The Queue is used for sending messages to the port and main loop takes responses back. I've used no serial.readline() method, because of different end-line char, and I have found the usage of io classes to be too much fuss.
Depends on what you run in that thread.
If that's your code, then you can implement a stop condition (see other answers).
However, if what you want is to run someone else's code, then you should fork and start a process. Like this:
import multiprocessing
proc = multiprocessing.Process(target=your_proc_function, args=())
proc.start()
now, whenever you want to stop that process, send it a SIGTERM like this:
proc.terminate()
proc.join()
And it's not slow: fractions of a second.
Enjoy :)
My solution is:
import threading, time
def a():
t = threading.currentThread()
while getattr(t, "do_run", True):
print('Do something')
time.sleep(1)
def getThreadByName(name):
threads = threading.enumerate() #Threads list
for thread in threads:
if thread.name == name:
return thread
threading.Thread(target=a, name='228').start() #Init thread
t = getThreadByName('228') #Get thread by name
time.sleep(5)
t.do_run = False #Signal to stop thread
t.join()
I find it useful to have a class, derived from threading.Thread, to encapsulate my thread functionality. You simply provide your own main loop in an overridden version of run() in this class. Calling start() arranges for the object’s run() method to be invoked in a separate thread.
Inside the main loop, periodically check whether a threading.Event has been set. Such an event is thread-safe.
Inside this class, you have your own join() method that sets the stop event object before calling the join() method of the base class. It can optionally take a time value to pass to the base class's join() method to ensure your thread is terminated in a short amount of time.
import threading
import time
class MyThread(threading.Thread):
def __init__(self, sleep_time=0.1):
self._stop_event = threading.Event()
self._sleep_time = sleep_time
"""call base class constructor"""
super().__init__()
def run(self):
"""main control loop"""
while not self._stop_event.isSet():
#do work
print("hi")
self._stop_event.wait(self._sleep_time)
def join(self, timeout=None):
"""set stop event and join within a given time period"""
self._stop_event.set()
super().join(timeout)
if __name__ == "__main__":
t = MyThread()
t.start()
time.sleep(5)
t.join(1) #wait 1s max
Having a small sleep inside the main loop before checking the threading.Event is less CPU intensive than looping continuously. You can have a default sleep time (e.g. 0.1s), but you can also pass the value in the constructor.
Sometimes you don't have control over the running target. In those cases you can use signal.pthread_kill to send a stop signal.
from signal import pthread_kill, SIGTSTP
from threading import Thread
from itertools import count
from time import sleep
def target():
for num in count():
print(num)
sleep(1)
thread = Thread(target=target)
thread.start()
sleep(5)
pthread_kill(thread.ident, SIGTSTP)
result
0
1
2
3
4
[14]+ Stopped

How to run infinite loops within threading in python

I've looked everywhere and it seems like the threads I write should work. I've checked many other threads about it and tutorials. I can't seem to run infinite loops in threads. Despite what I do, only the first thread works/prints.
Here is the code for just methods.
import threading
def thread1():
while True:
print("abc")
def thread2():
while True:
print ("123")
if __name__ == "__main__":
t1 = threading.Thread(target=thread1())
t2 = threading.Thread(target=thread2())
t1.start
t2.start
t1.join
t2.join
Removing the prentheses at the end of calling the functions with target=causes nothing to print so I keep that in there.
Here is the class/object version.
from threading import Thread
class Thread1(Thread):
def __init__(self):
Thread.__init__(self)
self.daemon = True
self.start
def run():
while True:
print ("abc")
class Thread2(Thread):
def __init__(self):
Thread.__init__(self)
self.daemon = True
self.start
def run():
while True:
print ("123")
Thread1.run()
Thread2.run()
both never get to printing 123 and I can't figure out why. It looks like infinite loops shouldn't be an issue because they are being run in parallel. I tried time.sleep (bc maybe the GIL stopped it idk) so thread2 could run while thread1 was idle. Didn't work.
For the first example:
if __name__ == "__main__":
t1 = threading.Thread(target=thread1)
t2 = threading.Thread(target=thread2)
t1.start()
t2.start()
t1.join()
t2.join()
Pass the function, not the result of calling the function, to threading.Thread as its target.
For the section example. Don't call run. Call start. After creating an instance.
from threading import Thread
class Thread1(Thread):
def __init__(self):
Thread.__init__(self)
self.daemon = True
def run():
while True:
print ("abc")
class Thread2(Thread):
def __init__(self):
Thread.__init__(self)
self.daemon = True
def run():
while True:
print ("123")
Thread1().start()
Thread2().start()
Your parentheses are in the wrong places in the first version.
As currently written, you are passing the result of calling thread1 when creating t1; since that call never returns, you never actually create a thread. So you need to remove those parentheses.
But you don't include the parentheses where you are trying to call the start and join methods, so the threads never actually got started even when you didn't use the extra parentheses when creating the threads.

How to end with a thread from the main thread?

I'm looking for this question online but I can not find any way to do it directly I'm trying the following
class Test(Thread):
def __init__(self):
Thread.__init__(self)
def run(self):
for i in range(3):
time.sleep(1)
print(i)
def main():
test = Test()
test.start()
del test
time.sleep(5)
print('end')
main()
the only way to stop the thread is from the run method when the code ends but I can not find any way to end the thread.
You can't. All you can do is ask it nicely (by implementing some sort of inter thread communication like a threading.Queue object, then making your thread check it for instructions) and hope for the best.
You can use this simple approach to stop/kill/end a child thread from the parent thread using some variable that is being checked in child thread periodically:
from threading import Thread
from time import time, sleep
class Test:
some_var = True
def __init__(self):
self.t = Thread(target=self.worker)
#self.t.setDaemon(True)
self.t.start()
def worker(self):
while self.some_var is True:
print("%s > I'm running" % str(time()))
test = Test()
sleep(2)
test.some_var = False
print("End!")
Let me know if I didn't understand your question, but I think I've answered your question "How to end with a thread from the main thread?".

how can stop only thread but program should keep running in python

import time
import threading
class Check(threading.Thread):
def __init__(self):
self.stopped = False
threading.Thread.__init__(self)
def run(self):
i = 0
while not self.stopped:
time.sleep(1)
i = i + 1
print(i)
if(i==5):
self.stopped = True
inst = Check()
inst.start()
You have to set up your own mechanism for stopping a thread--Python doesn't have a built-in way to do it. This is actually a common problem among many languages, not just Python.
import time
import threading
class Check(threading.Thread):
def __init__(self):
threading.Thread.__init__(self)
# An event can be useful here, though a simple boolean works too since
# assignment is atomic in Python.
self.stop_event = threading.Event()
def run(self):
i = 0
while not self.stop_event.is_set():
time.sleep(1)
i = i + 1
print(i)
if(i==5):
self.stopped = True
def stop(self):
# Tell the thread to stop...
self.stop_event.set()
# Wait for the thread to stop
self.join()
inst = Check()
inst.start()
# Do stuff...
time.sleep(1)
inst.stop()
# Thread has stopped, but the main thread is still running...
print("I'm still here!")
Here I use an event to signal whether or not the thread should stop. We add a stop method to signal the event and then wait for the thread to finish processing before continuing. This is very simplistic, but hopefully it gives you the idea of the kind of strategy you can take. It gets much more complicated if you want to handle error conditions like being informed if an error occurred in the run() method or if the body of the run() method is taking too long, etc.

How to make a stoppable thread with a target function that is an infinite loop

Suppose I would like to run a function, called run_forever(), in a thread, but still have it 'stoppable' by pressing Ctrl+C. I've seen ways of doing this using a StoppableThread subclass of threading.Thread, but these seem to involve 'copying' the target function into that subclass. I would like to instead keep the function 'where it is'.
Consider the following example:
import time
import threading
def run_forever(): # An externally defined function which runs indefinitely
while True:
print("Hello, world!")
time.sleep(1)
class StoppableThread(threading.Thread):
"""Thread class with a stop() method. The thread itself has to check
regularly for the stopped() condition."""
def __init__(self, *args, **kwargs):
super(StoppableThread, self).__init__(*args, **kwargs)
self._stop = threading.Event()
def stop(self):
self._stop.set()
def stopped(self):
return self._stop.isSet()
def run(self):
while not self.stopped():
run_forever() # This doesn't work
# print("Hello, world!") # This does
self._stop.wait(1)
thread = StoppableThread()
thread.start()
time.sleep(5)
thread.stop()
The target function run_forever is itself a while-loop which never exits. However, to get the desired behavior the wait() command has to be inside that while-loop, as I understand it.
Is there any way of achieving the desired behavior without modifying the run_forever() function?
I doubt it's possible.
BTW, have you tried the second solution with
ThreadWithExc from the post you linked earlier?
It works if the loop is busy pure Python(eg no sleep), otherwise I'd switch to multiprocessing and kill subprocess. Here is the code that hopefully exits gracefully(*nix only):
from multiprocessing import Process
from signal import signal, SIGTERM
import time
def on_sigterm(*va):
raise SystemExit
def fun():
signal(SIGTERM, on_sigterm)
try:
for i in xrange(5):
print 'tick', i
time.sleep(1)
finally:
print 'graceful cleanup'
if __name__=='__main__':
proc = Process(target=fun)
proc.start()
time.sleep(2.5)
proc.terminate()
proc.join()

Categories