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

Is threading module really parallel in python or do we need to use multiprocessing?

所以,我写了这个简单的代码来检查 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()