如何在Python中更改正在运行的线程中的参数值

2024-10-01 13:32:42 发布

您现在位置:Python中文网/ 问答频道 /正文

如何更改在线程(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”变量。如果没有线程我也做不到,因为我还有其他代码部分在执行并行任务。我能做什么? 谢谢!在


Tags: 函数runselfifinitdef线程thread
2条回答

首先要学习的最好的方法是不要改变来自不同线程的变量。通过队列通信:

import threading
import queue

def drive(speed_queue):
    speed = 1
    while True:
        try:
            speed = speed_queue.get(timeout=1)
            if speed == 0:
                break
        except queue.Empty:
            pass
        print("speed:", speed)

def main():
    speed_queue = queue.Queue()
    threading.Thread(target=drive, args=(speed_queue,)).start()
    while True:
        speed = int(input("Enter 0 to Exit or 1/2/3 to continue: "))
        speed_queue.put(speed)
        if speed == 0:
            break

main()

除了很多语法错误之外,整个过程也是错误的——将工作从run委托给另一个方法是没有意义的,但是即使有,最后一个while也会无限循环(如果它实际上被写成while True:),永远不会检查速度变化。在

另外,不要使用run()方法与线程接口-这是启动线程时调用的特殊方法,您应该单独处理自己的更新。在

您还应该花一些时间学习Python中的OOP,因为这不是一个类的制作方法。在

下面是一个你想做什么的例子,希望它能对你有所帮助:

import threading
import time


class MyThread (threading.Thread):

    def __init__(self, speed=0.1):
        self._speed_cache = 0
        self.speed = i
        self.lock = threading.RLock()
        super(MyThread, self).__init__()

    def set_speed(self, speed):  # you can use a proper setter if you want
        with self.lock:
            self.speed = speed

    def run(self):
        while True:
            with self.lock:
                if self.speed == 0:
                    print("Speed dropped to 0, exiting...")
                    break
                # just so we don't continually print the speed, print only on change
                if self.speed != self._speed_cache:
                    print("Current speed: {}".format(self.speed))
                    self._speed_cache = self.speed
            time.sleep(0.1)  # let it breathe

try:
    input = raw_input  # add for Python 2.6+ compatibility
except NameError:
    pass

current_speed = 3  # initial speed

blink_thread = MyThread(current_speed)
blink_thread.start()

while current_speed != 0:  # main loop until 0 speed is selected
    time.sleep(0.1)  # wait a little for an update
    current_speed = int(input("Enter 0 to Exit or 1/2/3 to continue\n"))  # add validation?
    blink_thread.set_speed(current_speed)

另外,请注意线程不是并行执行任何东西它使用GIL在上下文之间切换,但是从来没有两个线程绝对同时执行。互斥锁(Mutex,lock)在这个意义上只是为了确保操作的原子性,而不是实际的独占性。在

如果您需要一些东西来并行执行(如果您有多个核心,也就是说),您需要使用multiprocessing。在

相关问题 更多 >