Search code examples
pythonmultithreadingpython-multithreading

How to run a thread only when function is called?


I am coding a large ISA simulator project and I am trying to tackle it in Python. I am learning about threads and have a question related to running a thread. Here is my below code:

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():
....

Now this thread runs but I have many functions and classes in my Python file. As the _thread.start_new_thread(startBreakPoint, ("Thread-1", 5,)) is declared outside the function, would it run on the start of running the simulator it self? I would want it to simply run when startBreakPoint is called but not anytime else.


Solution

    • You should use the threading module's Thread class, not the internal _thread module.
    • You're starting the thread with startBreakPoint as its entry point; that's the function that will be run in another thread. If you want another thread (that does something, who knows what) to start when startBreakPoint is called, then startBreakPoint should be creating the thread (or maybe signaling a pre-started thread to wake up, using e.g. threading.Event()).

    (However, if this is an emulator/simulator and you're trying to implement some sort of breakpoint/debugger thing, I don't think a second thread is necessarily the right approach; instead, it sounds like your emulator loop should have a hook of some sort? Also, as an aside, the proliferation of global variables scares me...)