gpt4 book ai didi

python - 线程模块在 python 中真的是并行的还是我们需要使用多处理?

转载 作者:太空宇宙 更新时间:2023-11-04 01:09:18 24 4
gpt4 key购买 nike

所以,我写了这个简单的代码来检查 python 线程模块是否真的是并行的,我发现在这种情况下,

from threading import Thread, current_thread
import multiprocessing as mp
def callback(result):
print result

def run_sql(n):
print current_thread()
for i in range(n):
i=i+1
print 'done for ', current_thread()

if __name__=='__main__':
n=100000000
pool = mp.Pool(5)
threads= [ Thread(target=run_sql, args=(n,)) for i in range(5)]
for t in threads:
t.start()
for t in threads:
t.join()

我对 Pool.apply_async 进行了同样的尝试,它实际上是并行的。

def callback(result):
print result

def run_sql(n):
print current_thread()
for i in range(n):
i=i+1
print 'done for ', current_thread()

if __name__=='__main__':
print datetime.datetime.now()
n=100000000
pool = mp.Pool(5)
for i in range(10):
pool.apply_async(run_sql, args= (n,),callback=callback)
pool.close()
pool.join()

所以我的问题是,如果线程模块不是真正并行的,即使它节省了 IPC 并使用相同的内存区域,那么使用线程模块的意义何在?另外,线程实际上可以使用队列或其他东西并行吗?

最佳答案

看起来你一开始就加入了你的线程:

for t in threads:
t.start()
t.join()

IIRC,Thread.join 将等待线程完成,然后再继续(这意味着您在开始第二个线程之前等待第一个线程完成)...

通常,您需要 2 个循环:

for t in threads:
t.start()
# other stuff to do in the main thread...
for t in thread:
t.join()

关于python - 线程模块在 python 中真的是并行的还是我们需要使用多处理?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28682175/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com