简体   繁体   English

python multiprocessing,进程共享一个公共变量吗?

[英]python multiprocessing, do the processes share a common variable?

I have this: 我有这个:

#!/usr/bin/env python

import multiprocessing

class MultiprocessingTest(object):

    def __init__(self):
        self.cmd = ''

    def for_process_A(self):
        self.cmd = "AA"
        print "%s executing and cmd is %s" % (multiprocessing.current_process().name, self.cmd)


    def for_process_B(self):
        self.cmd = "BB"
        print "%s executing and cmd is %s" % (multiprocessing.current_process().name, self.cmd)


if __name__ == '__main__':

    obj =   MultiprocessingTest()

    process_A = multiprocessing.Process(target=obj.for_process_A, name='process_A')
    process_B = multiprocessing.Process(target=obj.for_process_B, name='process_B')

    process_A.start()
    process_B.start()


    process_A.join()
    process_B.join()

Question: 题:

Do the two processes share the variable cmd ? 这两个进程共享变量cmd吗?

Do both processes have a separate class MultiprocessingTest definition and work off of that? 这两个过程是否都有单独的类MultiprocessingTest定义并MultiprocessingTest工作依据?

Independent copies of which data exists in the two processes? 这两个过程中存在哪些数据的独立副本?

I am trying to understand from a theoretical standpoint what is actually happening here. 我试图从理论的角度理解这里实际发生的事情。 Can you please comment on that? 你能对此发表评论吗?

Test Run o/p: 测试运行o / p:

$ ./commonvar.py 

process_A executing and cmd is AA

process_B executing and cmd is BB

Processes don't share data. 进程不共享数据。 Each process is a separate container with following resources, generally speaking: 通常,每个进程都是具有以下资源的单独容器:

  • Code to execute 执行代码
  • Stack
  • Processor time 处理器时间

Processes interact with outside world through Pipes. 流程通过管道与外界交互。

So to answer your questions: 因此,回答您的问题:

  • Processes will not share cmd variable. 进程将不会共享cmd变量。
  • Processes will have separate copies of the class code. 进程将具有类代码的单独副本。
  • All the program data will be independent. 所有程序数据将是独立的。

Further Explanation: 进一步说明:

Behind the scenes, fork system call is used to create a process (assuming you are using *nix). 在后台,使用fork系统调用创建一个进程(假设您正在使用* nix)。 Processes are heavier compared to threads because of the overhead involved in switching the conext . 由于切换conext会涉及开销,因此与线程相比,进程要重得多

Changes which happen inside of multiprocessing shouldn't propagate back to the calling "thread" (or any of the other multiprocessing processes). 在多处理内部发生的更改不应传播回调用的“线程”(或任何其他多处理进程)。 If you want that sort of "shared-memory-like" behavior, you'll need to look into using a multiprocessing.Manager . 如果您想要这种“类似共享内存”的行为,则需要使用multiprocessing.Manager

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM