Python 告诉我分配给外部函数的线程未分配

问题描述 投票:0回答:2

我让这个程序有一个定时输入:

import time
from threading import Thread

def get_answer():
    answer = input ("ANSWER THE QUESTION!!!")

def runtime():
    time.sleep(1)
    timer = timer-1
    print (timer)
    if timer == 0:
        thread1.cancel()
        print ("hi")

timer = 5

# create two new threads
thread1 = Thread(target=get_answer)
thread2 = Thread(target=runtime)

# start the threads
thread1.start()
thread2.start()

# wait for the threads to complete
thread1.join()
thread2.join()

当我运行它时,我收到此错误:

Exception in thread Thread-2 (runtime):
Traceback (most recent call last):
  File "C:\Users\user1\AppData\Local\Programs\Python\Python310\lib\threading.py", line 1009, in _bootstrap_inner
    self.run()
  File "C:\Users\user1\AppData\Local\Programs\Python\Python310\lib\threading.py", line 946, in run
    self._target(*self._args, **self._kwargs)
  File "c:\Users\user1\Desktop\import time.py", line 9, in runtime
    timer = timer-1
UnboundLocalError: local variable 'timer' referenced before assignment

我该如何解决这个问题?我在线程运行之前设置了变量

timer
,那么为什么它还没有被分配呢?

python multithreading variables
2个回答
0
投票

以下是如何使用计时器处理输入:

from signal import signal, alarm, SIGALRM

TIMEOUT = 5

def get_answer(timeout):
    def handler(*args):
        raise Exception('Timeout')
    signal(SIGALRM, handler)
    alarm(timeout)
    try:
        return input ("ANSWER THE QUESTION!!! ")
    except Exception:
        pass
    finally:
        alarm(0)

print(get_answer(TIMEOUT))

所以,这里没有话题。如果在 TIMEOUT 秒内没有输入,get_answer()函数将返回 None。否则它将返回用户输入。


-1
投票

谢谢@玛丽亚

将变量设为全局变量,并将减法部分放入

while
循环中。

import time
import threading as t
from threading import Thread

class StoppableThread(t.Thread):
    def __init__(self):
        super().__init__()
        self.stop_flag = t.Event()

    def run(self):
        while not self.stop_flag.is_set():
            answer = input ("ANSWER THE QUESTION!!!")

    def stop(self):
        self.stop_flag.set()

global timer
timer = 5

"""def get_answer():
    answer = input ("ANSWER THE QUESTION!!!")"""

def runtime():
    global timer
    while True:
        time.sleep(1)
        timer = timer-1
        print (timer)
        if timer == 0:
            thread1.stop()
            break

# create two new threads
thread1 = StoppableThread()
thread2 = Thread(target=runtime)

# start the threads
thread1.start()
thread2.start()

# wait for the threads to complete
thread1.join()
thread2.join()
© www.soinside.com 2019 - 2024. All rights reserved.