Created
August 31, 2016 08:52
-
-
Save grhawk/d8187ab8d5dcec7649134e9a1955c9d8 to your computer and use it in GitHub Desktop.
A background thread in python with signal control
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import threading | |
import time | |
from sys import stdout | |
# Only data wihtin a class are actually shared by the threads | |
class Counter(object): | |
counter = 0 | |
stop = False | |
# Function that will be executed in parallel with the rest of the code | |
def function_1(): | |
for i in range(10): | |
if c.stop: return # With more will exit faster | |
time.sleep(2) | |
c.counter += 1 | |
if c.stop: return | |
# Create a class instance | |
c = Counter() | |
# Thread function_1 | |
d = threading.Thread(target=function_1) | |
d.start() | |
# Exit the thread properly before exiting... | |
try: | |
for j in range(100): | |
# print 'asd' | |
stdout.write('\r{:}'.format(c.counter)) | |
stdout.flush() | |
time.sleep(1) | |
except: | |
c.stop = True |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment