Python:了解线程模块 [英] Python: Understanding Threading Module
问题描述
在学习Python的 threading 模块时,我运行了一个简单的测试.有趣的是,线程是顺序运行的,而不是并行运行的.是否可以修改此测试代码,以便程序以与多处理相同的方式执行线程:并行执行?
While learning Python's threading module I've run a simple test. Interesting that the threads are running sequentially and not parallel. Is it possible to modify this test code so a program executes the threads in same fashion as multiprocessing does: in parallel?
import threading
def mySlowFunc(arg):
print "\nStarting...", arg
m=0
for i in range(arg):
m+=i
print '\n...Finishing', arg
myList =[35000000, 45000000, 55000000]
for each in myList:
thread = threading.Thread(target=mySlowFunc, args=(each,) )
thread.daemon = True
thread.start()
thread.join()
print "\n Happy End \n"
修改后的代码:
此版本的代码将启动以并行"方式运行的6个线程".但是,即使有6个线程,实际上也只使用了两个CPU线程(另外6个物理CPU线程将处于空闲状态并且不执行任何操作).
REVISED CODE:
This version of the code will initiate 6 'threads' running in 'parallel'. But even while there will be 6 threads only two CPU's threads are actually used (6 other Physical CPU threads will be idling and doing nothing).
import threading
def mySlowFunc(arg):
print "\nStarting " + str(arg) + "..."
m=0
for i in range(arg):
m+=i
print '\n...Finishing ' + str(arg)
myList =[35000000, 45000000, 55000000, 25000000, 75000000, 65000000]
for each in myList:
thread = threading.Thread(target=mySlowFunc, args=(each,) )
thread.daemon = False
thread.start()
print "\n Bottom of script reached \n"
推荐答案
来自
等待直到线程终止.这将阻塞调用线程,直到被调用join()方法的线程终止(正常或通过未处理的异常终止),或者直到发生可选的超时为止.
Wait until the thread terminates. This blocks the calling thread until the thread whose join() method is called terminates – either normally or through an unhandled exception – or until the optional timeout occurs. 只需创建一个线程列表,然后在启动其中的每一个线程之后将其加入即可. Just create a list of threads and join them after launching every single one of them. 线程是并行执行的,您可以将python的线程想像成具有单核的计算机,事实是,python的线程最适合IO操作(读取/写入大文件,通过套接字发送数据,那类的东西).如果需要CPU功能,则需要使用多处理模块 The threads are executing in parallel, you can think of python's threads like a computer with a single core, the thing is, python's threads are best for IO operations (reading/writing a big file, sending data through a socket, that sort of thing). If you want CPU power you need to use the multiprocessing module 这篇关于Python:了解线程模块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!