1

How do i properly use the join(timeout) function in the follow example? the timeout didn't seem to have an effect on the main thread execution. From the docs, the main thread is blocked until threads join or timeouts.

import threading,time

class Server(threading.Thread):

    def __init__(self, hostname):
        super(Server, self).__init__()
        self.__hostname = hostname

    def run(self):
        print self.__hostname+' left'
        time.sleep(5)
        print self.__hostname+' back'
        sem.release()

#init
sem = threading.BoundedSemaphore(4)
threads = []

for x in xrange(1,5):
    sem.acquire()
    t = Server('thread '+str(x))
    threads.append(t)
    t.start()

for t in threads:
    t.join(2)

print 'why is this line executed by main thread 5 seconds after, not 2?'
user3388884
  • 4,748
  • 9
  • 25
  • 34

1 Answers1

1

You have a for loop that tries to join each of the 4 threads with a 2 second timeout.

The first .join() call takes the full 2 seconds and then times out. The second does the same. The third thread finishes after 5 seconds (1 second after the third .join(2) call), and the 4th is already done when it's joined. 2 + 2 + 1 = 5.

Wooble
  • 87,717
  • 12
  • 108
  • 131