Skip to content Skip to sidebar Skip to footer

How To Avoid Waiting For A Thread To Finish Execution - Python

I have the following structure defined in Python - There are two threads. Each thread scans the branch vertically downwards and prints its value. On reaching the end of that bran

Solution 1:

There are different approaches you can take, but I would like to point out two of them:

First, use Semaphore, this one as close as your code but it is not preferable really:

from threading import Semaphore

defprintTags(DevObj, s):
    ...
    s.release()
    ...

import threading, thread

# temp1 points to Block A.# temp2 points to Block B.


s = Semaphore(0)
threads = [
    threading.Thread(target=printTags, args=(THING_TO_DO,s))
    for THING_TO_DO in THINGS_TO_DO
]
for t in threads:
    t.start()

whileTrue:
    s.aquire()
    for t in threads:
        # give more work

More preferred option is to use producer/consumer pattern:

from threading import Semaphore

STOP = object()

defprintTags(queue):
    whileTrue:
        thing_to_process = queue.get()
        if thing_to_process is STOP:
            returnelse:
            #process import threading, thread

# temp1 points to Block A.# temp2 points to Block B.

THREAD_COUNT = 2
s = Semaphore(0)
threads = [
    threading.Thread(target=printTags, args=(queue,))
    for _ in xrange(THREAD_COUNT)
]

for thing in things:
    queue.put(thing)
for _ in xrange(THREAD_COUNT):
    queue.put(STOP)

for t in threads:
    t.start()

Post a Comment for "How To Avoid Waiting For A Thread To Finish Execution - Python"