Search
 
SCRIPT & CODE EXAMPLE
 

PYTHON

pause and resume threads python

class Me(threading.Thread):
    def __init__(self):
        threading.Thread.__init__(self)
        #flag to pause thread
        self.paused = False
        # Explicitly using Lock over RLock since the use of self.paused
        # break reentrancy anyway, and I believe using Lock could allow
        # one thread to pause the worker, while another resumes; haven't
        # checked if Condition imposes additional limitations that would 
        # prevent that. In Python 2, use of Lock instead of RLock also
        # boosts performance.
        self.pause_cond = threading.Condition(threading.Lock())

    def run(self):
        while True:
            with self.pause_cond:
                while self.paused:
                    self.pause_cond.wait()

                #thread should do the thing if
                #not paused
                print 'do the thing'
            time.sleep(5)

    def pause(self):
        self.paused = True
        # If in sleep, we acquire immediately, otherwise we wait for thread
        # to release condition. In race, worker will still see self.paused
        # and begin waiting until it's set back to False
        self.pause_cond.acquire()

    #should just resume the thread
    def resume(self):
        self.paused = False
        # Notify so thread will wake after lock released
        self.pause_cond.notify()
        # Now release the lock
        self.pause_cond.release()
Comment

PREVIOUS NEXT
Code Example
Python :: boxplot python count of data 
Python :: softmax for nparray 
Python :: handdle close window action in pyqt5 
Python :: aritmetics to a value in a dict python 
Python :: create matrix with complex python 
Python :: http://techforcurious.website/simulation-of-pendulum-vpython-tutorial-visual-python/ 
Python :: pandas apply return dataframe 
Python :: def identity_block(X, f, filters, training=True, initializer=random_uniform): 
Python :: the grandest staircase of them all foobar solution 
Python :: miktex python install linux 
Python :: how to filter csv file by columns 
Python :: pandas row printed horizontally 
Python :: dictionary changed size during iteration after pop function 
Python :: python quick sort 
Python :: kivy lang 
Python :: SQLAlchemy Users to JSON code snippet 
Python :: get false positives from confusoin matrix 
Python :: wx.SingleInstanceCheckerindexmodules 
Python :: skip security check selenium linkedin python 
Python :: naiveDateTime last week from current time 
Python :: wxpython mainloop 
Python :: python get_loc not returning number 
Python :: onetomany field 
Python :: blockchain.py 
Python :: Handling single exception 
Python :: check entries smaller 0 after groupby 
Python :: gpg --verify Python-3.6.2.tgz.asc 
Python :: multiplication table for number python codewars 
Python :: if python 
Python :: python print list 
ADD CONTENT
Topic
Content
Source link
Name
8+2 =