Skip to content

Instantly share code, notes, and snippets.

@jaekookang
Forked from ruedesign/thread.py
Created April 7, 2018 04:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jaekookang/044f85b8d19155e970e0edf0481998bc to your computer and use it in GitHub Desktop.
Save jaekookang/044f85b8d19155e970e0edf0481998bc to your computer and use it in GitHub Desktop.
Python thread sample with handling Ctrl-C
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys, time, threading, abc
from optparse import OptionParser
def parse_options():
parser = OptionParser()
parser.add_option("-t", action="store", type="int", dest="threadNum", default=1,
help="thread count [1]")
(options, args) = parser.parse_args()
return options
class thread_sample(threading.Thread):
def __init__(self, name):
threading.Thread.__init__(self)
self.name = name
self.kill_received = False
def run(self):
while not self.kill_received:
# your code
print self.name, "is active"
time.sleep(1)
def has_live_threads(threads):
return True in [t.isAlive() for t in threads]
def main():
options = parse_options()
threads = []
for i in range(options.threadNum):
thread = thread_sample("thread#" + str(i))
thread.start()
threads.append(thread)
while has_live_threads(threads):
try:
# synchronization timeout of threads kill
[t.join(1) for t in threads
if t is not None and t.isAlive()]
except KeyboardInterrupt:
# Ctrl-C handling and send kill to threads
print "Sending kill to threads..."
for t in threads:
t.kill_received = True
print "Exited"
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment