【发布时间】:2022-01-03 02:31:46
【问题描述】:
如何与另一个进程共享来自一个进程的值? 显然我可以通过多线程而不是多处理来做到这一点。 多线程对我的程序来说很慢。
我无法显示我的确切代码,所以我做了这个简单的例子。
from multiprocessing import Process
from threading import Thread
import time
class exp:
def __init__(self):
self.var1 = 0
def func1(self):
self.var1 = 5
print(self.var1)
def func2(self):
print(self.var1)
if __name__ == "__main__":
#multithreading
obj1 = exp()
t1 = Thread(target = obj1.func1)
t2 = Thread(target = obj1.func2)
print("multithreading")
t1.start()
time.sleep(1)
t2.start()
time.sleep(3)
#multiprocessing
obj = exp()
p1 = Process(target = obj.func1)
p2 = Process(target = obj.func2)
print("multiprocessing")
p1.start()
time.sleep(2)
p2.start()
预期输出:
multithreading
5
5
multiprocessing
5
5
实际输出:
multithreading
5
5
multiprocessing
5
0
【问题讨论】:
-
这能回答你的问题吗? Sharing a complex object between processes?
-
这取决于您要共享的数据。我推荐使用队列docs.python.org/3/library/…
标签: python python-3.x multiprocessing python-multiprocessing python-multithreading