首页 > 解决方案 > 对任何参数都不满意的多处理

问题描述

我有一个数字列表,我想要 2 个不同的 cpu 内核来打印每个列表的一半。1 个核心从开头开始,其他核心从中间开始。

我做了2次尝试。两者都给出错误,告诉我在 这里尝试我的其他尝试和错误示例

错误 1 ​​= 参数太多,只需要 1

错误 2 = 1 arg 不可迭代

(下定决心)

代码 1(不迭代)

import multiprocessing as mp
import numpy as np

A = np.linspace(0,99999999,999999)

def print_stuff(i):
    for j in i:    # i want two seperate proccessores to print half of this list each 
        print(A[j]) 

def do_stuff():
    print("doing stuff")
    kk = range(int(len(A/2)))
    kk2 = [] # to use to index places in the lists
    for i in kk:
        kk2.append(i+kk[-1])
    print(len(kk2))

    p1 = mp.Process(target = print_stuff, args = kk,)
    p2 = mp.Process(target = print_stuff, args = kk2,)
    p1.start()
    p2.start()

    # This will terminate the thread when they done their job(s)
    p1.join()
    p2.join()
    print("done stuff")

if __name__ == "__main__":
    do_stuff()

代码 2(迭代)

import multiprocessing as mp
import numpy as np

A = np.linspace(0,99999999,999999)

def print_stuff(i):
    # i want two seperate proccessores to print half of this list each 
    print(A[j]) 

def do_stuff():
    print("doing stuff")
    kk = range(int(len(A/2)))
    kk2 = []
    for i in kk:
        kk2.append(i+kk[-1])
    print(len(kk2))
    for i in range(int(len(A/2))):
        p1 = mp.Process(target = print_stuff, args = kk[i],)
        p2 = mp.Process(target = print_stuff, args = kk2[i],)
        p1.start()
        p2.start()

    # This will terminate the thread when they done their job(s)
        p1.join()
        p2.join()
    print("done stuff")

if __name__ == "__main__":
    do_stuff()

标签: pythonmultithreadingmultiprocessing

解决方案


第一个代码有问题,因为您在需要整数的地方传递了一个 Iterable。


推荐阅读