【发布时间】:2020-10-11 17:14:13
【问题描述】:
而不是多次打印数字。我知道它适用于线程,但我想尝试使用多处理,因为它使用更少的 cpu
list = ['1', '2', '3', '4', '5']
def number():
while len(list) > 0:
print(list[0])
list.pop(0)
def start():
if __name__ == '__main__':
threads = []
for i in range(int(input('Threads: '))):
threads.append(Process(target=number))
for thread in threads:
try:
thread.start()
sleep(0.3)
except Exception as e:
print(e)
for thread in threads:
try:
thread.join()
except Exception as e:
print(e)
start()
if __name__ == '__main__':
input()
我正在尝试进行多处理,我希望输出类似于
1
2
3
4
5
【问题讨论】:
-
你是在 Windows 上(产生新的 python 的地方)还是在 linux/mac 上(新的进程用于分叉的地方)?
-
顺便说一句,不要将变量命名为“list”,因为它掩盖了创建列表的内置
list。 -
多处理不会降低 CPU 使用率。 MP增加它。 MP 的目标是最大化 CPU 使用以最小化 执行时间。在您的代码中,您添加了
sleep,所以我认为您不会通过 MP 获得任何好处。 -
您在模块级别调用
start(),然后在if __name__ ...保护器下有一个额外的input()。我认为应该只是start在 if 下。但它也回答了平台问题 - 在 Windows 上,start()将在每个子进程上再次调用,从而创建无限数量的子进程。 -
请注意,number 函数不是线程安全的。打印的项目可能不是弹出的项目,因为另一个线程很可能已经执行并在那个时候弹出了值。我怀疑这就是为什么你在那里有
sleep(.3)。但实际上这意味着前一两个线程将完成所有工作,最后的线程会发现列表已经为空。
标签: python python-3.x python-2.7 python-requests