我有一个在不同线程中运行的函数,当一个事件被引发时,它调用一个函数,该函数是作为参数提供给它的,如下所示:
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),但我不知道如何传递。我不能多次调用(on_press)。我的目标是(func)能够在异步引发事件时修改(pos)。
任何帮助都将不胜感激。
发布于 2020-10-26 21:49:27
要在线程之间共享值,只需使它们在所有方法中都可访问(全局变量或更好的类)。
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()https://stackoverflow.com/questions/64535924
复制相似问题