我刚开始使用 Python 并偶然发现了线程本地内存。我写了一个使用线程的小程序:
#!/usr/bin/env python3
import logging
import signal
import threading
import time
class WorkerThread(threading.Thread):
def __init__(self, idx):
threading.Thread.__init__(self)
self.thread_index = idx
self.thread_alive = True
def run(self):
logging.info(f'Thread {self.thread_index} is starting up!')
while self.thread_alive:
logging.info(f'Thread {self.thread_index} is still running.')
time.sleep(1)
logging.info(f'Thread {self.thread_index} is stopping!')
def kill(self):
self.thread_alive = False
def main():
logging.basicConfig(format = '%(levelname)s: %(message)s', level = logging.INFO)
def signal_handler(sig, frame):
logging.info('Ctrl+c pressed, killing threads and shutting down ...')
nonlocal threads
for thread in threads:
thread.kill()
signal.signal(signal.SIGINT, signal_handler)
logging.info('Signal handler …Run Code Online (Sandbox Code Playgroud)