I’m looking to have a class (subclassed from threading.Thread) that is initialised and started from multiple places in a program. What I want to avoid is if the thread is already running from somewhere else, if another place in the program trys to start it
t= somemodule.TheThread(some,args)
t.start()
the program can carry on (but the thread only starts if the same thread isn’t already running here, or elsewhere).
I can think of a few not very elegant ways to achieve this with setting flags, but there must be a nice way of dealing with this. I looked at singleton type patterns with decorators or overriding new but the main problem is that if I keep the same instance is that you can’t (that I’m aware) call start more than once, even if the thread has finished.
I thought about having the thread object created in anther object which can check to see if the current thread is still running, but I couldn’t work out how to keep this thread safe.
Anyone got any ideas?
You should use a function to create and start the thread, and that function can use its own bookkeeping to know whether the thread has been started already or not. Don’t forget to make that bookkeeping thread-safe!
Trying to make the caller believe he is creating and starting a thread, when maybe he isn’t, is more trouble than it is worth. Encapsulating this common operation in a function is a good idea in any case, and gives you the control you’re seeking.