如何更改在线程(python)中无限循环中运行的函数的参数? 我不熟悉线程和python,但这是我想做的(简化)
class myThread (threading.Thread):
def __init__(self, i):
threading.Thread.__init__(self)
def run(i):
self.blink(i)
def blink(i):
if i!=0:
if i==1:
speed=0.10
elif i==2:
speed=0.20
elif i==3:
speed=0.30
while(true):
print("speed\n")
i=3
blinkThread=myThread(i)
blinkThread.start()
while(i!=0):
i=input("Enter 0 to Exit or 1/2/3 to continue\n")
if i!=0:
blinkThread.run(i)
显然,这段代码给出了有关run()方法的错误。我想在无限循环中运行blink()函数,但要更改“I”变量。如果没有线程我也做不到,因为我还有其他代码部分在执行并行任务。我能做什么? 谢谢!在
首先要学习的最好的方法是不要改变来自不同线程的变量。通过队列通信:
除了很多语法错误之外,整个过程也是错误的——将工作从run委托给另一个方法是没有意义的,但是即使有,最后一个
while
也会无限循环(如果它实际上被写成while True:
),永远不会检查速度变化。在另外,不要使用
run()
方法与线程接口-这是启动线程时调用的特殊方法,您应该单独处理自己的更新。在您还应该花一些时间学习Python中的OOP,因为这不是一个类的制作方法。在
下面是一个你想做什么的例子,希望它能对你有所帮助:
另外,请注意线程不是并行执行任何东西它使用GIL在上下文之间切换,但是从来没有两个线程绝对同时执行。互斥锁(Mutex,lock)在这个意义上只是为了确保操作的原子性,而不是实际的独占性。在
如果您需要一些东西来并行执行(如果您有多个核心,也就是说),您需要使用
multiprocessing
。在相关问题 更多 >
编程相关推荐