utopia-rise / godot-kotlin-jvm

Godot Kotlin JVM Module
MIT License
562 stars 38 forks source link

Game does not exit when non-daemon thread is running in the JVM #566

Open MartinHaeusler opened 5 months ago

MartinHaeusler commented 5 months ago

If we create a regular thread in Kotlin which keeps running, like so:

@RegisterClass
class MyButton : Button() {

    @RegisterFunction
    override fun _pressed() {
        thread {
            GD.print("Sleeping")
            Thread.sleep(TimeUnit.HOURS.toMillis(1))
            GD.print("Wake up!")
        }

    }
}

... then the game window will not exit properly when clicking on the window close ("x") button. Hitting the "stop" button in the editor still works.

The workaround is to declare the thread as a daemon thread:

    thread(daemon = true){
        // ...
    }

... as this will not prevent the JVM from exiting.

I don't think that this needs to have super high priority, but if a library would spawn threads (e.g. an async HTTP client might do that) and doesn't permit control over the creation of the thread, then this can become an issue.

Maybe this can be handled on the C++ side? It works when stopping the game via the godot editor "stop" button after all.