python - 为什么我的代码不能在多个线程上运行?
问题描述
我一直在尝试对我的代码进行多线程处理,它仍然可以工作,但只使用了我的 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()
输出符合预期,但仅在一个线程上运行。
解决方案
也许是这样的:
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()
推荐阅读
- python-3.x - Python 3 格式 csv 左对齐并重新写入新的 csv
- python - 如何在 tensorflow 中监控准确度(度量准确度不可用)
- json - React Native Unexpected token < in JSON at position 0
- sql - 如何格式化没有小数的十进制值?
- flutter - 在构建期间调用 Flutter setState() 或 markNeedsBuild()
- python - 如果出现连续数字,则打破循环
- ruby-on-rails - 使用包含或预加载时,ActiveRecord 关联返回空结果
- sql - 使用 SQL 查询标记控制
- unicode - shell 中 Unicode 字符的行为差异
- ruby-on-rails - 在基于 selenium 的项目中使用 simplecov 需要一些帮助