简体   繁体   中英

Why Python Multiprocess class doesn't change the attribute?

#!/usr/bin/env python
from multiprocessing import Process

class Signprocess(Process):
  """docstring for SignThread"""
  def __init__(self):
    super(SignThread, self).__init__()
    self.result = False


  def run(self):
    self.result = True
    print 123

process= Signprocess()
print process.result
process.start()
print process.result
process.join()
print process.result

Here is the output

False
False
123
False

It's really strange, output 123 indicates that run() method is actually executed, but result attribute is never set to True , Why?

Process represents a forked process, not a thread. After the fork occurs (before self.result = True is executed), the memory space becomes unlinked; changes in one process do not affect the other process unless explicitly performed on shared memory or the results are communicated via some other form of IPC. Read more of the multiprocessing documentation; it provides many different ways to communicate data back and forth, but plain Python object state is not one of those ways.

Alternatively, if the goal is to use threads, not processes, change the import line to from multiprocessing.dummy import Process , which gets you the multiprocessing API backed by threads, not processes; threads share memory space, so you would see your expected result, though in computationally expensive threading cases, you would not gain much from parallelism due to CPython's GIL.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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