__main__函数创建了一个107的size,并用两个threads执行工作。然后创建了一个jobs列表,用于存储分离的线程。threading.Thread对象将list_append函数作为参数,并将它附加到jobs列表。
最后,jobs分别开始并分别“joined”。join()方法阻塞了调用的线程(例如主Python解释器线程)直到线程终止。在打印完整的信息到控制台之前,确认所有的线程执行完成。
# thread_test.pyimport randomimport threadingdef list_append(count, id, out_list):
"""
Creates an empty list and then appends a
random number to the list 'count' number
of times. A CPU-heavy operation!
"""
for i in range(count):
out_list.append(random.random())if __name__ == "__main__":
size = 10000000 # Number of random numbers to add
threads = 2 # Number of threads to create
# Create a list of jobs and then iterate through
# the number of threads appending each thread to
# the job list
jobs = []
for i in range(0, threads):
out_list = list()
thread = threading.Thread(target=list_append(size, i, out_list))
jobs.append(thread)
# Start the threads (i.e. calculate the random number lists)
for j in jobs:
j.start()
# Ensure all of the threads have finished
for j in jobs:
j.join()
print "List processing complete."
我们能在控制台中调用如下的命令time这段代码
time python thread_test.py
将产生如下的输出
List processing complete.
real 0m2.003s
user 0m1.838s
sys 0m0.161s
注意user时间和sys时间相加大致等于real时间。这表明我们使用线程库没有获得性能的提升。我们期待real时间显著的降低。在并发编程的这些概念中分别被称为CPU时间和挂钟时间(wall-clock time)