如何仅在调用函数时运行一个线程?

How to run a thread only when function is called?

我正在编写一个大型 ISA 模拟器项目,我正试图在 Python 中解决它。 我正在学习线程并有一个与 运行ning 线程相关的问题。 这是我的以下代码:

def ex1():
....
   startBreakPoint(threadName, delay)
....

def ex2():
....

def startBreakPoint(threadName, delay):
    lastStatementRun = 0
    isBreakpoint = None
    aString = None
    global machine_state
    global Running
    global machine_error
    global PC
    global dictReference
    global programArray
    global Paused
    global Uninitialized
    global No_Program
    global Normal_Halt
    global Abnormal_Halt
    global breakpointOn
    machine_state = Running
    while machine_state == Running and not machine_error:
        # enable stop button as true
        aString = str(PC).strip()
        if aString in dictReference:
            lastStatementRun = int(dictReference.get(aString))
        fetchNextInstruction()
        try:
            time.sleep(delay)
        except InterruptedError:
            print("Interrupted")
        if not machine_error:
            execute()
        isBreakpoint = bool(programArray[lastStatementRun][0])
        if machine_state == Running and isBreakpoint:
            machine_state = Paused
            print("Stopped for breakpoint")
    if machine_state == Uninitialized or machine_state == No_Program:
        return
    if machine_state == Normal_Halt or Abnormal_Halt:
        restart()
    machine_error = False
    # validate()
    breakpointOn = True

try:
    _thread.start_new_thread(startBreakPoint, ("Thread-1", 5,))
except:
    print("Error: unable to start thread")

while 1:
    pass

def ex3():
...

def ex4():
....

现在这个线程 运行s 但我有很多函数和 类 在我的 Python 文件中。由于 _thread.start_new_thread(startBreakPoint, ("Thread-1", 5,)) 是在函数外部声明的,它会 运行 在 运行 自身的模拟器开始时吗?我希望它在调用 startBreakPoint 时简单地 运行 而不是其他任何时候。

  • 您应该使用 threading 模块的 Thread class,而不是内部 _thread 模块。
  • 您正在以 startBreakPoint 作为入口点启动线程;这是将在另一个线程中 运行 的函数。如果你想在调用 startBreakPoint 时启动另一个线程(做某事,谁知道),那么 startBreakPoint 应该创建线程(或者可能发出信号通知预先启动的线程唤醒,使用例如 threading.Event()).

(但是,如果这是一个 emulator/simulator 并且您正在尝试实现某种 breakpoint/debugger 的东西,我认为第二个线程不一定是正确的方法;相反,听起来你的模拟器循环应该有某种钩子?另外,顺便说一句,全局变量的激增让我害怕......)