开发者

Python threaded code not acting threaded

开发者 https://www.devze.com 2023-02-08 16:44 出处:网络
Why doesn\'t this code \"act\" threaded?(Please see the output.) import time from threading import Thread

Why doesn't this code "act" threaded? (Please see the output.)

import time
from threading import Thread

def main():
    for nums in [range(0,5), range(5,10)]:
        t = Spider(nums)
        t.start()
        print 'started a thread'
        t.join()
    print "done"

class Spider(Thread):
    def __init__(self, nums):
        Thread.__init__(self)开发者_StackOverflow中文版
        self.nums = nums
    def run(self):  # this is an override
        for num in self.nums:
            time.sleep(3)  # or do something that takes a while
            print 'finished %s' % (num, )

if __name__ == '__main__':
    main()

Output:

started a thread
finished 0
finished 1
finished 2
finished 3
finished 4
started a thread
finished 5
finished 6
finished 7
finished 8
finished 9
done


When you say t.join(), you're telling it to wait for the thread to end.

This means, you're asking it to make a thread, start it, then wait for the thread to end before making a new one.

If you want it to act multithreaded, you'll need to move the join()s outside of the loop.

def main():
    # We will store the running threads in this
    threads = []
    # Start the threads
    for nums in [range(0,5), range(5,10)]:
        t = Spider(nums)
        t.start()
        print 'started a thread'
        threads.append(t)
    # All the threads have been started
    # Now we wait for them to finish
    for t in threads:
        t.join()
    print "done"

See also:

  • Documentation of Thread.join()


Your Thread join t.join blocks the main thread until the thread completes execution ( http://docs.python.org/library/threading.html#threading.Thread.join ). Change your code to look something like this:

def main():
  threads = [] 
  for nums in [range(0,5), range(5,10)]:
    t = Spider(nums)
    t.start()
    print 'started a thread'
    threads.append(t)
  for t in threads: t.join()
  print "done"


You need to start both the threads first, and then join with them once they are both running.

0

精彩评论

暂无评论...
验证码 换一张
取 消