-1

First of all I am new to the python multithreading. I have a program that detect hands of set of photos using multiple parallel threads and after detecting main program do some functions based on that hand detected images. functions are on main thread. But now both functions and hand detection threads are running parallel. I need to pause main thread until finishes the execution of hand detection threads.Sorry for my language mistakes.

#Thread creation function

def callThreads(self, imageLst):
        global taskLock, tasks
        for tid in range(1, 10, 1):  ## 1,11,1
            thread = handdetect.detectHandThread(imageLst, tid, 'thread_{}'.format(tid), tasks, taskLock,
                                                 obj_detection_graph_queue, obj_detLock)
            thread.start()
            threads.append(thread)
            print("[INFO] Thread {} created and added to the pool...".format(tid))
# main() function of the programme
..............
self.callThreads(filenames)

Some functions()
............



1 Answers1

0

As you maintain the list threads already, you can just call join on all of its elements:

for thread in threads:
  thread.join()
tevemadar
  • 12,389
  • 3
  • 21
  • 49
  • Yes. I did join. But then all the threads in the list are executing one by one. I need to run all of them in parallel. – Sandun Gunasekara May 13 '19 at 12:00
  • It is actually not one by one. Only runs first thread that pop out from the list. Others are waiting until thread 1 finishes. So then all the photo process is done by thread 1 one by one. – Sandun Gunasekara May 13 '19 at 12:08
  • @SandunGunasekara well, the point is that this loop ends when all of the threads have finished. Their order does not matter, a `thread2` is free to finish while the loop is still waiting for `thread1`, and then when the loop tries to wait for `thread2`, it will just notice it has finished already and proceed to `thread3`, and so on. – tevemadar May 13 '19 at 12:24
  • @SandunGunasekara however there is one thing about threads, the Global Interpreter Lock, a scary monster even Wikipedia [writes](https://en.wikipedia.org/wiki/Global_interpreter_lock) about, but https://stackoverflow.com/questions/1294382/what-is-the-global-interpreter-lock-gil-in-cpython migth be a more useful reading. So if you saw your threads doing nothing, this was it (and presumalby on CPython), not the `join`. Check out [`multiprocessing`](https://docs.python.org/3/library/multiprocessing.html). – tevemadar May 13 '19 at 12:30