Embedded python with Thread in script not working properly

Hi Everyone,

I am facing a issue when trying to integrate the python313.dll into my application, when call the websocket in my application, the thread create in python script is not working properly. So I did a sample as below.

Here is what I did:

In my application, after initilize the python, I call PyImport_ImportModule to import my script, and after that, I uses pybind11::object(module.attr(“Initialize”)()).cast(); to call a function in the imported script. My script is something like below.

So the problem is that when I call the initialize function, the new thread will only work at the very beginning, but after exit the initilize funciton, the thread not working any more. I only see one result printed “count down 10” in my log.

Any one faced the issue before? Could you please kindly advise what did I missed out in this scenario?

from threading import Thread

def countdown(n):
    while n > 0:
        log(0, "count down " + str(n))
        n -= 1
        time.sleep(5)

def Initialize(): 
    t = Thread(target=countdown, args=(10,))
    t.start()
    return True

Does it work for you in the Python REPL or as a regular script?

No such issue if I use python.exe to trigger such script. The thread created in python script works fine when run by python.exe. The issue only happens when I try to use the embedded python from my own GUI application.

Than it sounds like it’s an issue with the embedded Python in your GUI application.

You probably need to wait for the thread before exiting the main function.

If you’re doing the waiting outside of the Initialize function, then you’ll need to release the GIL in order for any other Python threads to make any progress (they’re all waiting to acquire that lock). Look up the pybind11 docs for how to release the GIL.