Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/multithreading/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/bash/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 多线程(?):循环中的手动干扰_Python_Multithreading - Fatal编程技术网

Python 多线程(?):循环中的手动干扰

Python 多线程(?):循环中的手动干扰,python,multithreading,Python,Multithreading,我一直在研究一种直接在运行的模块中更改变量的方法。 我想要实现的是正在运行负载测试,并且我可以手动调整调用速度或其他任何方式 下面是我刚刚创建的一些代码(没有测试e.d.),只是给你一个想法 class A(): def __init__(self): self.value = 1 def runForever(self): while(1): print self.value def setValue(self,

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

下面是我刚刚创建的一些代码(没有测试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():-)

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

退房

下面是一个演示,演示如何按照您的要求进行操作。我更喜欢使用队列来直接调用线程/进程

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()
导入队列#!!警告如果使用多处理,请使用multiprocessing.Queue
导入线程
导入时间
def main():
q=队列。队列()
测试仪=测试仪(q)
tester.start()
尽管如此:
用户输入=原始输入(“以秒为单位的新周期或(q)uit:”)
如果用户输入.lower()
打破
尝试:
新速度=浮动(用户输入)
除值错误外:
新建速度=无#忽略垃圾
如果新速度不是无:
q、 put(新速度)
q、 put(测试仪停止令牌)
类测试仪(线程。线程):
停止标记=“”
定义初始化(self,q):
threading.Thread.\uuuuu init\uuuuuu(自)
self.q=q
自身速度=1
def运行(自):
尽管如此:
#退出队列
尝试:
item=self.q.get(block=False)#不要挂起
队列除外。空:
项目=无#什么也不做
如果项目:
#请求时停止
如果item==self.STOP\u标记:
中断#停止此线程循环
#否则,检查是否有新的速度
尝试:
自速度=浮动(项目)
除值错误外:
通过#任何你喜欢的未知输入
#做你的事
self.main_代码()
def主_代码(自身):
时间。睡眠(自我。速度)#或任何你想做的事
如果uuuu name uuuuuu='\uuuuuuu main\uuuuuuu':
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()

我将不得不研究如何将代码转换成某种可线程化的东西。。。有什么建议吗?