Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
524 views
in Technique[技术] by (71.8m points)

python - Difference between Process.run() and Process.start()

I am struggling to understand the difference between run() and start(). According to the documentation, run() method invokes the callable object passed to the object's constructor, while start() method starts the process and can be called only once.

I tried an example below:

def get_process_id(process_name):
    print process_name, os.getpid()

p1 = multiprocessing.Process(target=get_process_id, args=('process_1',))
p2 = multiprocessing.Process(target=get_process_id, args=('process_2',))

p1.run()
p2.run()
p1.start()
p2.start()

The results are below:

process_1 35138
process_2 35138
process_1 35141
process_2 35142

When I use run(), it shows that p1 and p2 uses the same process. But when I use start(), they give the two difference ones. Is it because calling run() doesn't have anything to do with the process that calls it but just calling the function (which is get_process_id in this example)?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You are not supposed to call process.run() explicitly. It's the method which invokes your specified target function unless you override it when you subclass Process. It normally gets called within the new child while it bootstraps. It does nothing else than calling the target function.

# multiprocessing.process.BaseProcess

def run(self):
    '''
    Method to be run in sub-process; can be overridden in sub-class
    '''
    if self._target:
        self._target(*self._args, **self._kwargs)

When you call it in your parent process, it gets executed in your parent process like any other method.

process.start() is the method which you're supposed to call in your parent to create the new process in the first place.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...