首页 > 解决方案 > 为什么我的代码不能在多个线程上运行?

问题描述

我一直在尝试对我的代码进行多线程处理,它仍然可以工作,但只使用了我的 cpu 的 15%(我有 8 个线程,所以那是 1 个线程)。

我已经从堆栈溢出和 youtube 尝试了许多脚本到多线程,但没有一个有效。

import threading

n=2

def crazy():
    global n
    while True:
        n = n*2
        print(n)

threads = []
for i in range(4):
    t = threading.Thread(target=crazy)
    threads.append(t)
    t.start()

输出符合预期,但仅在一个线程上运行。

标签: pythonpython-3.xmultithreading

解决方案


也许是这样的:

from multiprocessing.dummy import Pool

n = 2


def crazy(_):
    global n
    while True:
        n = n * 2
        print(n)

threads = []
pool = Pool(8)
pool.map(crazy, range(8))
pool.close()
pool.join()

推荐阅读