A great tip from [WayBack] python multithreading wait till all threads finished:
ou need to use join method of
Threadobject in the end of the script.t1 = Thread(target=call_script, args=(scriptA + argumentsA)) t2 = Thread(target=call_script, args=(scriptA + argumentsB)) t3 = Thread(target=call_script, args=(scriptA + argumentsC)) t1.start() t2.start() t3.start() t1.join() t2.join() t3.join()Thus the main thread will wait till
t1,t2andt3finish execution.
I’ve used a similar construct that’s used by the multi-threading code I posted a few ways ago (on Passing multiple parameters to a Python method: the * tag) in the ThreadManager class below.
But first some of the other links that helped me getting that code as it is now:
- [WayBack] Python programming with threads (using
start() andjoin()) - [WayBack] How to manage python threads results?
- [WayBack] How to declare an array in Python?: initialising an empty instance array variable
- Python 3: [WayBack]
Thread.start; [WayBack]Thread.join - Python 2: [WayBack]
Thread.start; [WayBack]Thread.join - [WayBack] In the following method definitions, what does the * and ** do for param2? def foo(param1, *param2): def bar(param1, **param2)
Example:
class ThreadManager:
def __init__(self):
self.threads = []
def append(self, *threads):
for thread in threads:
self.threads.append(thread)
def runAllToCompletion(self):
## The loops are the easiest way to run one methods on all entries in a list; see https://stackoverflow.com/questions/2682012/how-to-call-same-method-for-a-list-of-objects
# First ensure everything runs in parallel:
for thread in self.threads:
thread.start()
# Then wait until all monitoring work has finished:
for thread in self.threads:
thread.join()
# here all threads have finished
def main():
## ...
threadManager.append(
UrlMonitorThread(monitor, "http://%s" % targetHost),
SmtpMonitorThread(monitor, targetHost, 25),
SmtpMonitorThread(monitor, targetHost, 587),
SshMonitorThread(monitor, targetHost, 22),
SshMonitorThread(monitor, targetHost, 10022),
SshMonitorThread(monitor, targetHost, 20022))
threadManager.runAllToCompletion()
–jeroen






