0

Hi why is my KeyboardInterrupt: is not stoping my program when i hit control c or control x? this is my current code.

I am using python Threading that runs 2 function coinPulser and coinPulserDone.

import threading
import time

lock = threading.Lock()
counter = 0
input = 3

def coinPulser ():
    global counter
    global input
    lock.acquire()
    try:
        while counter < input:
            counter+=1
            time.sleep(.1)
            if counter in [1,3,5]:
                print(counter)
        return counter
    finally:
        lock.release()

def coinPulserDone ():
    while True:
        print(coinPulser())


try:
    coinpulser = threading.Thread(target = coinPulser)
    coinpulser.start()
    coinpulserdone = threading.Thread(target = coinPulserDone)
    coinpulserdone.start()
except KeyboardInterrupt:
    coinpulser.stop()
    coinpulserdone.stop()
    print('Thread Stops')
  • 1
    Possible duplicate of [threading ignores KeyboardInterrupt exception](https://stackoverflow.com/questions/3788208/threading-ignores-keyboardinterrupt-exception) – ytu Sep 02 '18 at 03:05

1 Answers1

0

I suspect the problem is that your code exits your try/except block before you press Cntr-C. You need to add some form of a loop that will hold it in that block. A simple loop such as

while True:
    time.sleep(1)

before your except line should do the trick.

Steven W. Klassen
  • 1,401
  • 12
  • 26