0

I have a parent script running 10 child scripts simultaneously through threading.

Each child is a logger of data from an API, is on a while True: loop and saves datas regarding the data in a json file. When the code is haulted the json sometimes looses integrity and looks like this:

["2016_02_21_18_46_41", 1], ["2016_02_21_18_46_42", 1], ["2016_02_21_18_46_4

meaning that it can't be opened using json.loads.

Marco Bonelli
  • 63,369
  • 21
  • 118
  • 128
David Hancock
  • 1,063
  • 4
  • 16
  • 28
  • @VincentSavard I posted the other post, this one is different though. – David Hancock Feb 23 '16 at 19:25
  • @DavidHancock What exactly would be different in this question? How would the answer to this question be substantially different than the answer to the original question? If you would like to change the first question, you are free to edit it. – Kyle Pittman Feb 23 '16 at 19:26

2 Answers2

2

you can change while True to

should_run = True
while should_run:

and change should_run to False when you want to close it gracefully. if you stop your script with CTRL+C you should surround it with this

try:
    somthing()
except KeyboardInterrupt:
    should_run = False 

if the thread are not daemon threads then your program will wait for them to finish before exiting

DorElias
  • 2,243
  • 15
  • 18
  • wow such elegance. So i'm using Liclipse and pressing 'terminate' does this still count as a 'KeyboardInterupt' ? – David Hancock Feb 23 '16 at 19:37
  • no, according to this http://stackoverflow.com/questions/677531/is-it-possible-for-eclipse-to-terminate-gently-instead-of-using-sigkill – DorElias Feb 23 '16 at 19:58
1

You can use threading events, which are flags you can set from outside the thread loop:

A factory function that returns a new event object. An event manages a flag that can be set to true with the set() method and reset to false with the clear() method. The wait() method blocks until the flag is true.

Declare a threading event in the thread class init:

self._stopevent = threading.Event()

Add to your thread class the following method:

def stop_thread(self):
    self._stopevent.set()

In the while loop:

while not self._stopevent.isSet():

Then just call stop_event to cleanly stop the thread.

Aviah Laor
  • 3,620
  • 2
  • 22
  • 27