该程序有两个主要功能,它们正在运行
while True
循环。 clickSpot
函数等待signal_found
为True
然后点击self.spot
,屏幕上的一个位置,然后将self.actions_done
递增1。self.spot
被getInputFromUser
改变,同时也显示self.actions_done
,由clickSpot
改变。
这是我正在运行的代码示例:
import multiprocessing
class Program():
def __init__(self):
self.spot = (0,0)
self.do_action = False
self.actions_done = 0
second_process = multiprocessing.Process(target=self.clickSpot)
getInputFromUser()
def getInputFromUser(self):
while True:
self.spot = ...input changed by user
...displays self.actions_done
...input from user that toggles self.exit
def clickSpot(self):
while True:
signal_found = check_signal() ...returns True or False
if signal_found == True:
click(self.spot)
self.actions_done += 1
signal_found = False
def exit(self):
...closes GUI in getInputFromUser and stops clickSpot process
我目前的实现涉及多线程。但是,当与 GUI 交互时,两个线程都会变慢。我还没有设法让它与多处理一起工作。
预期的结果是让
getInputFromUser
和clickSpot
同时运行,共享self.spot
和self.actions_done
.
您的问题似乎是您应该使用多线程和Event Objects和conditon objects
“正确”做的事情while True:
signal_found = check_signal()
if signal_found == True:
是一个繁忙的等待,如果您将其移植到多处理,这将使您的应用程序使用线程变慢或在您的 CPU 上烧一个洞,它应该被替换为
threading.condition
.
condition_obj1 = threading.Condition()
condition_obj2 = threading.Condition()
def clickSpot(self):
while True:
condition_obj1.wait() # .notify() instead of setting signal_found=True
click(self.spot)
self.actions_done += 1
def getInputFromUser(self):
while True:
condition_obj2.wait() # notified inside a GUI event that listens on user input
self.spot = ...input changed by user
...displays self.actions_done
...input from user that toggles self.exit
这没有回答最初的问题,即如何通过多处理共享变量。
好吧,有 multiprocessing 版本的条件和事件,还有 multiprocessing.Value 和 multiprocessing.Queue 用于在进程之间共享值,它允许共享值,但这不是您当前需要的。