【问题标题】:Python & MultiprocessingPython 和多处理
【发布时间】:2020-01-05 17:54:12
【问题描述】:
import multiprocessing

def main(a):
    while True:
        print(a)

p = multiprocessing.process(target=main(1))
p0 = multiprocessing.process(target=main(2))
p.start()
p0.start()

如果你运行它只是打印的代码:

1
1
1
1
1
1
1
1

它实际上应该输出这样的东西

1
2
1
1
2
2
2
1
2
1
2

我该如何解决这个问题:我从今天早上开始就在做研究。请发送帮助。

【问题讨论】:

    标签: python python-3.x parallel-processing multiprocessing


    【解决方案1】:

    这符合您的要求吗?

    from multiprocessing import Process
    
    def fun(a):
        while True:
            print(a)
    
    if __name__ == '__main__':
        p = Process(target=fun, args=(1,)) # that's how you should pass arguments
        p.start()
        p1 = Process(target=fun, args=(2,))  
        p1.start()
    

    输出:

    1
    2
    1
    2
    2
    2
    2
    2
    2
    1
    

    【讨论】:

    • 如果我没有要传递的参数,我该怎么做?
    • 没有参数是什么意思?您的函数需要一个 fun(a): (a) 意味着它需要一些变量。如果您不希望它能够接受任何变量,请将其更改为 fun()
    猜你喜欢
    • 1970-01-01
    • 2014-11-20
    • 2021-09-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-18
    相关资源
    最近更新 更多