user2229183 user2229183 - 2 months ago 6
Python Question

How to start and stop thread?

Sorry for the old question. I have clarified it. How can I start an stop thread with my poor thread class?

EDIT: It is in loop, I want to restart it again at the beginning of the code. How can I do start-stop-restart-stop-restart?

My class:

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


In the main code, I want:

inst = Concur()

while conditon:
inst.start()

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

Answer

This is David Heffernan's idea fleshed-out. The example below runs for 1 second, then stops for 1 second, then runs for 1 second, and so on.

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()