我写了一个简单的例子来说明我到底在敲什么。可能有一些非常简单的解释,我只是想念。
import time
import multiprocessing as mp
import os
class SomeOtherClass:
def __init__(self):
self.a = 'b'
class SomeProcessor(mp.Process):
def __init__(self, queue):
super().__init__()
self.queue = queue
def run(self):
soc = SomeOtherClass()
print("PID: ", os.getpid())
print(soc)
if __name__ == "__main__":
queue = mp.Queue()
for n in range(10):
queue.put(n)
processes = []
for proc in range(mp.cpu_count()):
p = SomeProcessor(queue)
p.start()
processes.append(p)
for p in processes:
p.join()
结果是:
PID: 11853
<__main__.SomeOtherClass object at 0x7fa637d3f588>
PID: 11854
<__main__.SomeOtherClass object at 0x7fa637d3f588>
PID: 11855
<__main__.SomeOtherClass object at 0x7fa637d3f588>
PID: 11856
<__main__.SomeOtherClass object at 0x7fa637d3f588>
无论每次初始化都发生在新进程中,对象地址都是相同的。任何人都可以指出什么问题。谢谢。
我也想知道这种行为,当我第一次在主进程中初始化同一个对象然后在其上缓存一些值,然后在每个进程上初始化同一个对象时。然后进程继承主进程对象。
import time
import multiprocessing as mp
import os
import random
class SomeOtherClass:
c = {}
def get(self, a):
if a in self.c:
print('Retrieved cached value ...')
return self.c[a]
b = random.randint(1,999)
self.c[a] = b
return b
class SomeProcessor(mp.Process):
def __init__(self, queue):
super().__init__()
self.queue = queue
def run(self):
pid = os.getpid()
soc = SomeOtherClass()
val = soc.get('new')
print("Value from process {0} is {1}".format(pid, val))
if __name__ == "__main__":
queue = mp.Queue()
for n in range(10):
queue.put(n)
pid = os.getpid()
soc = SomeOtherClass()
val = soc.get('new')
print("Value from main process {0} is {1}".format(pid, val))
processes = []
for proc in range(mp.cpu_count()):
p = SomeProcessor(queue)
p.start()
processes.append(p)
for p in processes:
p.join()
这里的输出是:
Value from main process 13052 is 676
Retrieved cached value ...
Value from process 13054 is 676
Retrieved cached value ...
Value from process 13056 is 676
Retrieved cached value ...
Value from process 13057 is 676
Retrieved cached value ...
Value from process 13055 is 676