多线程:循环中的手动干涉

2024-06-25 22:54:14 发布

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

我一直在寻找一种直接改变正在运行的模块中变量的方法。 我想要实现的是负载测试正在运行,并且我可以手动调整调用速度或其他任何方式。你知道吗

下面是我刚刚创建的一些代码(没有测试e.d.),只是给你一个想法。你知道吗

class A():
    def __init__(self):
        self.value = 1
    def runForever(self):
        while(1):
            print self.value
    def setValue(self, value):
        self.value = value

if __name__ == '__main__':
    #Some code to create the A object and directly apply the value from an human's input
    a = A()

    #Some parallelism or something has to be applied.
    a.runForever()
    a.setValue(raw_input("New value: "))

编辑#1:是的,我知道现在我再也不会碰到a.setValue():-)


Tags: 模块theto方法代码selfinputvalue
2条回答

您编写的伪代码与python中线程/多处理的工作方式非常相似。例如,您希望启动一个“永远运行”的线程,而不是直接修改内部速率值,您可能只需要通过一个给出新值的队列发送一条消息。你知道吗

查看this question。你知道吗

下面是一个演示如何做你所要求的事情。我更喜欢使用队列来直接调用线程/进程。你知道吗

import Queue  # !!warning. if you use multiprocessing, use multiprocessing.Queue
import threading
import time


def main():
    q = Queue.Queue()
    tester = Tester(q)
    tester.start()
    while True:
        user_input = raw_input("New period in seconds or (q)uit: ")
        if user_input.lower() == 'q':
            break
        try:
            new_speed = float(user_input)
        except ValueError:
            new_speed = None  # ignore junk
        if new_speed is not None:
            q.put(new_speed)
    q.put(Tester.STOP_TOKEN)

class Tester(threading.Thread):
    STOP_TOKEN = '<<stop>>'
    def __init__(self, q):
        threading.Thread.__init__(self)
        self.q = q
        self.speed = 1
    def run(self):
        while True:
            # get from the queue
            try:
                item = self.q.get(block=False)  # don't hang
            except Queue.Empty:
                item = None  # do nothing
            if item:
                # stop when requested
                if item == self.STOP_TOKEN:
                    break  # stop this thread loop
                # otherwise check for a new speed
                try:
                    self.speed = float(item)
                except ValueError:
                    pass  # whatever you like with unknown input
            # do your thing
            self.main_code()
    def main_code(self):
        time.sleep(self.speed)  # or whatever you want to do


if __name__ == '__main__':
    main()

下面是一个多线程示例。此代码将与python解释器一起工作,但与IDLE的python Shell不一起工作,因为raw_input函数的处理方式不同。你知道吗

from threading import Thread
from time import sleep

class A(Thread):
    def __init__(self):
        Thread.__init__(self)
        self.value = 1
        self.stop_flag = False

    def run(self):
        while not self.stop_flag:
            sleep(1)
            print(self.value)

    def set_value(self, value):
        self.value = value

    def stop(self):
        self.stop_flag = True


if __name__ == '__main__':
    a = A()
    a.start()
    try:
        while 1:
            r = raw_input()
            a.set_value(int(r))
    except:
        a.stop()

相关问题 更多 >