简体   繁体   中英

Python threaded code not acting threaded

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)
        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:

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"

您需要先启动两个线程,然后在它们都运行后再加入它们。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM