paupaulaz
paupaulaz

Reputation: 977

Python : call a function and wait for its thread(s) to finish

I am using Python to script a gdb session. My goal is to run a function whenever a breakpoint is hit, using gdb.events.stop.connect.

Here is my code in essence, which I call from gdb by running source main.py :

RESULT = None


def breakpoint_handler(event):
    global RESULT
    RESULT = do_something(event)  # boolean
    sleep(1)


def main():
    global RESULT
    gdb.events.stop.connect(breakpoint_handler)
    command = "some gdb command"
    gdb.execute(command)
    sleep(1)
    if RESULT:
        # do something
        pass
    else:
        # something else
        pass

main()

This code works, but only thanks to the sleep calls, that tries to make sure the gdb.execute(command)call actually finish executing the gdb command before continuing. There is only little documentation but my guess is that this function is threaded, which explains the effectiveness of the waitas a fix.

Is there a way to make this cleaner by waiting for the thread created by gdb.execute to finish processing, without having access to the body of this method ?

Upvotes: 0

Views: 387

Answers (1)

Boris Lipschitz
Boris Lipschitz

Reputation: 1641

You can set an event inside your callback and wait for it in your main thread. Here is an example, with the callback being called after 5 seconds by timer:

import threading

def some_callback():
    event.set()

event = threading.Event()
threading.Timer(5, some_callback).start()
event.wait()

Upvotes: 1

Related Questions