在windows和linux上运行时,以下代码具有不同的输出(均使用python2.7)
'''import_mock.py'''
to_mock = None
Run Code Online (Sandbox Code Playgroud)
'''test.py'''
import import_mock
from multiprocessing import Process
class A(object):
def __init__(self):
self.a = 1
self.b = 2
self.c = 3
def __getstate__(self):
print '__getstate__'
return { 'a': self.a, 'b': self.b,
'c':0 }
def func():
import_mock.to_mock = 1
a = A()
return a
def func1(a):
print a.a, a.b, a.c
print import_mock.to_mock
if __name__ == '__main__':
a = func()
p = Process(target=func1, args=(a,))
p.start()
p.join()
Run Code Online (Sandbox Code Playgroud)
在Windows上,输出是:
__getstate__
1 2 0
None
Run Code Online (Sandbox Code Playgroud)
这是我的预期
在linux上,它是:
1 2 3
1 …Run Code Online (Sandbox Code Playgroud) 对于Linux和WinXP,forking()和CreateProcess(带有所有必需的参数)分别是同一回事吗?
如果它们不同,那么有人可以用两种情况下的不同来解释这种差异吗?
谢谢
这是我为并行创建字典而编写的一些代码
并行化
if __name__ == "__main__":
import time
from multiprocessing import Pool
def assign_dict(alist):
return {x:x for x in alist}
my_dict = {}
size = 10000000
threshold=10000000
my_list=list(range(size))
start=time.time()
my_dict=assign_dict(my_list)
end=time.time()
print("check seq",end-start, " sec")
my_dict = {}
chunks = [my_list[i*threshold:(i+1)*threshold] for i in range(int(size/threshold))]
process_count = 7
pool = Pool(processes=process_count)
start = time.time()
inter_list = pool.map_async(assign_dict, chunks)
inter_list.wait()
inter_list=inter_list.get()
for some_dict in inter_list:
print("Combining...", time.time()-start, " sec elapsed")
my_dict = {**my_dict, **some_dict}
print("check 152002 as key ",my_dict[152002])
end=time.time()
print("check …Run Code Online (Sandbox Code Playgroud)