Skip to content

Instantly share code, notes, and snippets.

@ruedesign
Last active July 29, 2023 22:12
Show Gist options
  • Save ruedesign/5218221 to your computer and use it in GitHub Desktop.
Save ruedesign/5218221 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()
@joaoceron
Copy link

for python 3:
s/isAlive()/is_alive()/g

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment