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)
您无法看到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)
...这可能是你期望看到的,因为它是在打印完所有数字后发生的.
| 归档时间: |
|
| 查看次数: |
8456 次 |
| 最近记录: |