在Python中异步修改局部变量



我有一个在不同线程中运行的函数,当引发事件时,它会调用一个作为参数提供给它的函数,如下所示:

import keyboard
def func(arg):
pass
keyboard.on_press(func)

此(on_press(函数还将一个参数传递给(func(。

import keyboard

def func(arg):
...

def func2(a):
...

def func3(a):
...

def func4(a):
...

def main():
keyboard.on_press(func)
while True:
pos = func2(randint(10))
check = True
while check:
pos = func3(pos)
check = func4(pos)
main()

在上面的例子中,我想把(pos(传递给(func(,也想把参数(on_press(传递给。我不能多次打电话。我的目标是(func(能够在异步引发事件时修改(pos(。

任何帮助都将不胜感激。

要在线程之间共享一个值,只需使它们在所有方法中都可以访问(全局变量或更好的类(。

import keyboard
pos = randint(10)
def func():
global pos
...

def func2():
global pos
...

def func3():
global pos
...

def func4():
global pos
...

def main():
global pos
keyboard.on_press(func)
while True:
pos = func2()
check = True
while check:
pos = func3(pos)
check = func4(pos)
main()

如果该值对竞争条件敏感(即,不同的按键可以产生不同的值,并且顺序在应用程序中至关重要(,则必须引入互斥(Lock(。

from threading import Lock
class MyClass(object):
def __init__(self):
self.mutex = Lock()
self.pos = randint(10)

def func():
with self.mutex:
print(self.pos)
...

def func2():
with self.mutex:
print(self.pos)
...
def func3():
with self.mutex:
print(self.pos)
...
def func4():
with self.mutex:
print(self.pos)
...
def main():
keyboard.on_press(func)
while True:
with self.mutex:
self.pos = self.func2()
check = True
while check:
with self.mutex:
self.pos = self.func3()
check = self.func4()
if __name__ == "__main__":
MyClass().main()

最新更新