1

I'm trying to run a background timer while running other processes. I've used thread.Thread:

import threading
import random
import time
import sys
def timer(limit):
    time.sleep(limit)
    sys.exit()
def code():   
    dictionary=['hello','loading','dumb']
    word=[]
    c=random.choice(dictionary)
    answer=c
    for x in c:
        word.append(x)
    y=0
    words=''
    while y!=len(c):
        x=random.choice(word)
        word.remove(x)
        words=words+x
        y+=1
    print(words)
    guess=input()
    if guess==answer:
        print('NOICE')
    else:
        print("NUB")
    permit=input('Play Again?')
t1=threading.Thread(target=timer, args=(10,))
t2=threading.Thread(target=code)
t1.start()
t2.start()

That`s all my code. The problem is that when i run it, the timer waits for input before exiting. I want the timer to exit at ten second mark, whether or not input was entered. I thought that threading would make it so that the processes would not have to wait for each other. Help please? Oh, and I'm only a few days into python, so please keep your explanations simple. Thanks.

Qartx
  • 27
  • 9
  • You might find some useful answers [here](http://stackoverflow.com/questions/1335507/keyboard-input-with-timeout-in-python) if you're not using Windows. – John Apr 11 '17 at 14:41

1 Answers1

0

When you call sys.exit() in one of your threads, this does not affect the other threads. That is simply the nature of them! All threads are equal.

If you want to make a thread that will terminate when the program exits, it needs to be made into a daemon (think a slave under the master thread).

To do that:

slave_thread.daemon = True

And in your case:

t2.daemon = True

Thus, t2 will be terminated when the main thread exits. Do not confuse this main thread with t1. The main thread will continue executing while there are threads running (t1). But as soon as t1 exits, t2 will be terminated, because it is a daemon.

Remolten
  • 2,614
  • 2
  • 25
  • 29