Python多线程只能使用一个CPU

时间:2017-11-21 09:29:04

标签: python multithreading

我正在尝试创建不同的线程来处理8个核心。但是我看到代码创建了8个线程但只在我的macos上使用了100%左右。 为什么呢?

def runner(i):
    # do random stuff
    for a in range(0,1000000):
        i+=1
        5000 / 34 * i
        i + 400
        i / 20000
        i * 24440
        i+=1
        5000 / 34 * i
        i + 400
        i / 20000

q = queue.Queue()
threads = list()
for x in range(0,80):
    th = threading.Thread(target=runner,args=(x,))
    threads.append(th)

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

1 个答案:

答案 0 :(得分:2)

这是由于Python GIL(全局解释器锁)。它阻止Python线程在单个CPU上运行。 您可以在https://wiki.python.org/moin/GlobalInterpreterLock

了解更多相关信息
  

Python GIL是一个互斥锁,可以保护对Python对象的访问,防止多个线程同时执行Python字节码。这种锁是必要的,主要是因为CPython的内存管理不是线程安全的。

关于这个主题有多个问题,请查看SO

上的列表

如果您希望代码在多个CPU上运行,请查看multiprocessing模块。