在另一个线程中设置参数

时间:2012-07-24 19:57:48

标签: python multithreading

所以我有一个帖子:

import threading, time, serial, logging

class SerialThread(threading.Thread):

    # SerialThread class construcor
    def __init__(self, sleep):
        self.sleep = sleep
        threading.Thread.__init__(self,name = "SerialThread")
        self.setDaemon(1)

    # SerialThread method
    def run(self):

        # Do forever
        while 1:   

            # Sleep afther every loop
            time.sleep(self.sleep)
            print 'Doing some work!'

    def setSleep(self, sleep):
         self.sleep = sleep

然后在我的主线程中:

serialThread = SerialThread(60)
serialThread.start()

def changeSleep():
    serialThread.setSleep(80)

我正在从我的主代码开始这个帖子。但是现在当我想改变self.sleep数字时,我该怎么办?我尝试过这个简单而天真的解决方案,只需在线程类中创建一个方法,并在调用它时设置睡眠时间。显然这没有像我预期的那样工作。 一个很好的例子是受欢迎的。

编辑:添加我之前尝试的代码

编辑:所以它不会起作用,因为self.sleep总是60,因为我在开头设置它,即使我打电话给serialThread.setSleep(80)

编辑:不认为这是相关的,但我正在创建带有烧瓶的Web服务,并通过访问烧瓶路线调用serialThread.setSleep(80)。所以我猜瓶子也在单独的线程上运行,因为serialThread.setSleep(80)实际上并没有从主线程调用...

代码:

@app.route('/api/setConf', methods=['POST'])
def setConf():

    serialThread.setSleep(config.interval)

    return 'ok'

1 个答案:

答案 0 :(得分:0)

使用以下主体代码(以及线程代码中的有用打印)为我工作:

serialThread = SerialThread(3)
serialThread.start()

def changeSleep():
    serialThread.setSleep(6)

time.sleep(15)
changeSleep()
time.sleep(15)

输出:

sleeping for 3
Doing some work!
sleeping for 3
Doing some work!
sleeping for 3
Doing some work!
sleeping for 3
Doing some work!
sleeping for 3
Doing some work!
sleeping for 6
Doing some work!
sleeping for 6
Doing some work!
sleeping for 6