简体   繁体   English

Python 多处理共享变量

[英]Python multiprocessing shared variables

I'm trying to share the class instance/object variables with other processes that I start within it, since I need to run multiple function at the same time, to record macros from the keyboard & mouse and re-play them latter at the same timing.我正在尝试与我在其中启动的其他进程共享类实例/对象变量,因为我需要同时运行多个函数,从键盘和鼠标记录宏并同时重新播放它们定时。

I see that it's possible to use multiprocessing.Manager, but i'm using concurrent.futures.ThreadPoolExecutor.我看到可以使用 multiprocessing.Manager,但我使用的是 concurrent.futures.ThreadPoolExecutor。 is there a similar function there?那里有类似的功能吗?

I wrote the code below now to clarify.我现在写了下面的代码来澄清。 The actual code has a setState function for settings the recording state and such, and the key that's pressed doesn't get passed.实际代码有一个 setState 函数,用于设置录制状态等,按下的键不会被传递。 Also, the actual code obviously has a listener for the key presses and mouse moves, the getKey and getMove functions should be the ones appending to the list.此外,实际代码显然有一个按键和鼠标移动的监听器,getKey 和 getMove 函数应该是附加到列表中的函数。 The problem in this case is that the recording variable can't be accessed from the second process that should start recording moves once the "Insert" key is pressed.这种情况下的问题是,一旦按下“插入”键,就无法从应该开始记录移动的第二个进程访问记录变量。 A function in concurrent that's similar to Manager in multiprocessing would solve it, but i'm not sure what it's called or to use it.类似于多处理中的 Manager 的并发函数可以解决它,但我不确定它叫什么或使用它。

from concurrent.futures import ThreadPoolExecutor as Executor
import time

class recMacros(object):
    def __init__(self):
        self.recording = False

        self.lastKey = None
        self.lastMove = None

        self.mouseMoves = []
        self.keyPresses = []

        self.runMacros()


    def getTime(self):
        return time.time()

    def getKey(self):
        #return keyboard listener last key pressed
        return "W"

    def getMove(self):
        #return keyboard listener last key pressed
        return "W"

    def recMoves(self): 
        while True:
            while self.recording:
                mouseMove = self.getMove()
                if mouseMove != self.lastMove:
                    self.mouseMoves.append((mouseMove, self.getTime()))
                    self.lastMove = mouseMove

    def recPresses(self):
         while True:
             keyPress = self.getKey()
             if keyPress == "Insert":
                self.recording = True
             elif keyPress == "End":
                self.recording = False
             elif self.recording and keyPress != self.lastKey:
                self.keyPresses.append((keyPress, self.getTime()))
                self.lastKey = keyPress
             else:
                 print("Error")

    def recMacros(self):
        with Executor(max_workers=2) as e:
            e.submit(recPresses)
            e.submit(recMoves)

if __name__ == "__main__":
     recMacros()

I'd appreciate some quick direction since i'm in a rush.因为我很匆忙,所以我很感激一些快速的指导。 Thanks in advance提前致谢

@user2357112 supports Monica Here's the code I used to test the timing, to verify that ThreadPoolExecutor is like a process to comes to running the functions in parallel: @user2357112 支持 Monica 这是我用来测试计时的代码,以验证 ThreadPoolExecutor 就像一个并行运行函数的进程:

from concurrent.futures import ThreadPoolExecutor
import time

def printTime():
    print(f"Time: {time.time()}\n")


def runPro():
    with ThreadPoolExecutor(max_workers=3) as e:
        for i in range(3):
            e.submit(printTime)


runPro()

If you want to save something in a variable that every process can use, you can use queue .如果要将某些内容保存在每个进程都可以使用的变量中,则可以使用queue

  1. Import queue导入队列
import queue
  1. Create a shared variable创建共享变量
shared_var = queue.Queue(maxsize=0)

where maxsize is the maximum that can be saved in this queue其中maxsize是此队列中可以保存的最大值

  1. Edit shared variable in any process在任何进程中编辑共享变量
shared_var.put(item)
  1. Get the things in the variable获取变量中的东西
variable = shared_var.get()

There is a lot more you can do with queue , see the documentation .您可以使用队列执行更多操作,请参阅文档

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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