簡體   English   中英

如何啟動和停止線程

[英]How to start and stop a thread

如何使用我糟糕的線程類啟動和停止線程?

它處於循環中,我想在代碼開頭再次重新啟動它。 我怎樣才能開始-停止-重啟-停止-重啟?

我的課:

import threading

class Concur(threading.Thread):
    def __init__(self):
        self.stopped = False
        threading.Thread.__init__(self)

    def run(self):
        i = 0
        while not self.stopped:
            time.sleep(1)
            i = i + 1

在主代碼中,我想要:

inst = Concur()

while conditon:
    inst.start()

    # After some operation
    inst.stop()

    # Some other operation

您實際上不能停止然后重新啟動線程,因為在它的run()方法終止后您不能再次調用它的start()方法。 但是,您可以暫停一次,然后通過使用threading.Condition變量恢復其執行,以避免在檢查或更改其運行狀態時出現並發問題。

threading.Condition對象有一個關聯的threading.Lock對象和方法來等待它被釋放,並在發生時通知任何等待的線程。 這是一個從您的問題中的代碼派生的示例,它顯示了這一點。 在示例代碼中,我將Condition變量作為Thread子類實例的一部分,以更好地封裝實現並避免需要引入額外的全局變量:

from __future__ import print_function
import threading
import time

class Concur(threading.Thread):
    def __init__(self):
        super(Concur, self).__init__()
        self.iterations = 0
        self.daemon = True  # Allow main to exit even if still running.
        self.paused = True  # Start out paused.
        self.state = threading.Condition()

    def run(self):
        self.resume()
        while True:
            with self.state:
                if self.paused:
                    self.state.wait()  # Block execution until notified.
            # Do stuff...
            time.sleep(.1)
            self.iterations += 1

    def pause(self):
        with self.state:
            self.paused = True  # Block self.

    def resume(self):
        with self.state:
            self.paused = False
            self.state.notify()  # Unblock self if waiting.


class Stopwatch(object):
    """ Simple class to measure elapsed times. """
    def start(self):
        """ Establish reference point for elapsed time measurements. """
        self.start_time = time.time()
        return self

    @property
    def elapsed_time(self):
        """ Seconds since started. """
        try:
            return time.time() - self.start_time
        except AttributeError:  # Wasn't explicitly started.
            self.start_time = time.time()
            return 0



MAX_RUN_TIME = 5  # Seconds.
concur = Concur()
stopwatch = Stopwatch()

print('Running for {} seconds...'.format(MAX_RUN_TIME))
concur.start()
while stopwatch.elapsed_time < MAX_RUN_TIME:
    concur.resume()
    # Can also do other concurrent operations here...
    concur.pause()
    # Do some other stuff...

# Show Concur thread executed.
print('concur.iterations: {}'.format(concur.iterations))

這是大衛赫弗南的想法的充實。 下面的示例運行 1 秒,然后停止 1 秒,然后運行 ​​1 秒,依此類推。

import time
import threading
import datetime as DT
import logging
logger = logging.getLogger(__name__)

def worker(cond):
    i = 0
    while True:
        with cond:
            cond.wait()
            logger.info(i)
            time.sleep(0.01)
            i += 1

logging.basicConfig(level=logging.DEBUG,
                    format='[%(asctime)s %(threadName)s] %(message)s',
                    datefmt='%H:%M:%S')

cond = threading.Condition()
t = threading.Thread(target=worker, args=(cond, ))
t.daemon = True
t.start()

start = DT.datetime.now()
while True:
    now = DT.datetime.now()
    if (now-start).total_seconds() > 60: break
    if now.second % 2:
        with cond:
            cond.notify()

stop()的實現如下所示:

def stop(self):
    self.stopped = True

如果要重新啟動,則只需創建一個新實例並啟動它。

while conditon:
    inst = Concur()
    inst.start()

    #after some operation
    inst.stop()
    #some other operation

Thread文檔清楚地表明start()方法只能為類的每個實例調用一次。

如果要暫停和恢復線程,則需要使用條件變量

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM