Reputation: 99
I would like to have a thread running indefinitely, and have a „user interface“ (console command) by which I can stop a thread from running. How would I go about this?
import threading
from time import sleep
class Counter() :
index = 0
def __init__(self,offset) :
self.n = 0
self.offset = offset
self.nr = Counter.index
Counter.index = Counter.index + 1
self.bool = True
def start(self) :
def commence() :
while self.bool :
print(str(self.nr)+": "+str(self.n))
self.n = self.n + 1
sleep(self.offset)
threading.Thread(target=commence,args=()).start()
Counter(1).start()
Upvotes: 0
Views: 112
Reputation: 5037
Here's one way to do this:
import threading
from time import sleep
class Counter:
index = 0
def __init__(self, offset):
self.n = 0
self.offset = offset
self.nr = Counter.index
Counter.index = Counter.index + 1
self.lock = threading.Lock()
self.bool = True
def start(self):
def commence():
while True:
with self.lock:
if self.bool == False:
break
print(str(self.nr)+": "+str(self.n))
self.n = self.n + 1
sleep(self.offset)
thr = threading.Thread(target=commence, args=())
thr.start()
input("Please hit ENTER key to stop counter")
with self.lock:
self.bool = False
thr.join()
Counter(1).start()
Here's an example to deal with multiple counters.
import threading
from time import sleep
class Counter(threading.Thread):
index = 0
def __init__(self, offset):
super().__init__()
self.n = 0
self.offset = offset
self.nr = Counter.index
Counter.index = Counter.index + 1
self.lock = threading.Lock()
self.bool = True
def stop(self):
with self.lock:
self.bool = False
self.join()
def run(self):
while True:
with self.lock:
if self.bool == False:
break
print(f"Counter offset {self.offset} {self.nr}:{self.n}")
self.n = self.n + 1
sleep(max(self.offset, 1))
num_counters = 3
counters = []
for i in range(num_counters):
counter = Counter(i)
counter.start()
counters.append(counter)
counters_stopped = 0
while counters_stopped < num_counters:
counter_to_kill = int(input("Enter the counter offset to kill"))
the_counter = counters[counter_to_kill]
counters[counter_to_kill] = None
the_counter.stop()
counters_stopped += 1
print(f'Stopped counter at offset {counter_to_kill}')
print("All counters stopped")
Upvotes: 1