0

So i have a thread:

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

And then in my main thread i do:

serialThread = SerialThread(60)
serialThread.start()

def changeSleep():
    serialThread.setSleep(80)

Im am starting this thread from my main code. But now when i want to change the self.sleep number what should i do? I have tried this simple and naive solution to just create a method in the thread class, and when its called it sets the sleep time. Apparently this didnt work as i expected. A good example would be welcome.

EDIT: added the code i tried before

EDIT: So it wont work as the self.sleep is always 60 as i set it in the beginning, even afther i call the serialThread.setSleep(80)

EDIT: Didnt think this is relevant but im creating web service with flask and serialThread.setSleep(80) is called by accessing the flask route. So i guess flask runs also on separate thread and because of that serialThread.setSleep(80) is not actually called from the main thread...

Code:

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

    serialThread.setSleep(config.interval)

    return 'ok'
4

1 回答 1

0

Works for me with the following main body code (and a helpful print in the thread code):

serialThread = SerialThread(3)
serialThread.start()

def changeSleep():
    serialThread.setSleep(6)

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

Output:

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
于 2012-07-24T20:30:07.153 回答