等待线程使用join完成.很基本的

PFr*_*ise 3 python multithreading join

我有一个非常基本的任务,但我有一个问题使我的主线程等待我生成的所有其他线程完成.

这段代码没有做太多任何事情,它只是作为一个线程练习.

这是我的代码:

import time
from threading import Thread

def printNumbers(lowEnd, highEnd):
    while(lowEnd <= highEnd):
        print(repr(lowEnd))
        lowEnd += 1


countTo = 100000

#Test using 1 thread.        
startSingleThread = time.clock()
printNumbers(0,countTo)
elapsedSingleThread = (time.clock() - startSingleThread)

#Test using 10 threads
numberOfThreads      = 10
countAmountPerThread = countTo/numberOfThreads

startTenThread = time.clock()
for i in range(numberOfThreads):
    threadLowEnd  = i*countAmountPerThread
    threadHighEnd = (i+1)*countAmountPerThread
    t = Thread(target=printNumbers, args=(threadLowEnd,threadHighEnd,))
    t.start()

#Join all existing threads to main thread.
for thread in threading.enumerate():
    if thread is not threading.currentThread():
        thread.join()

elapsedTenThread = (time.clock() - startTenThread)

print("Time for 1 thread: " + repr(elapsedSingleThread))
print("time for 10 threads: " + repr(elapsedTenThread))
Run Code Online (Sandbox Code Playgroud)

Jos*_*Lee 6

您无法看到stderr,因为您正在向stdout打印这么多,但是您有这个错误:

Traceback (most recent call last):
  File "test.py", line 29, in <module>
    for thread in threading.enumerate():
NameError: name 'threading' is not defined
Run Code Online (Sandbox Code Playgroud)

如果我添加import threading到顶部,我得到这个输出:

Time for 1 thread: 1.0224820000000001
time for 10 threads: 1.421281
Run Code Online (Sandbox Code Playgroud)

...这可能是你期望看到的,因为它是在打印完所有数字后发生的.

  • @PFranchise:任务是IO绑定的.您可能在Windows上,它具有缓慢的控制台输出.如果你将输出重定向到一个文件(`python your_script.py> out.txt`)它应该快得多([1个线程为0.05秒,10个进程为0.02秒](http://ideone.com/nQk4H)) (2认同)