0 votes

Hi,

Has anyone got Threads going from C# scripts in G3RC2? Mine is crashing immediately I try to thread.Start(obj, "method"). Is this supposed to be working from C# scripts atm?

Briefly I'm just trying to get a simple producer-consumer queue going, with the main thread putting stuff onto the queue and the background (Start-ed) thread consuming off the queue. Crashes even when the consumer background thread does nothing, though, simply when it's Start-ed.

in Engine by (24 points)
edited by

Did a small rewrite to start the Thread from GDScript, and for the Thread.start()ed script to be written in GDScript that then calls onto my C# stuff. This still fails, although the Thread will start successfully (I can see a debug print coming out from the Threaded GDScript code) but fails with the Windows exception at the point it tries to call out to the C# code.

In fact even if I try to call a totally non-existent C# method from the threaded GDScript, I still get the Windows exception rather than a "method not found" type error. So it must be something to do with the C# engine being run up whilst in a Thread blowing up, before it even gets as far as checking for valid methods etc.

Anyone got C# code successfully running in a Thread?

In this issue I raised :

https://github.com/godotengine/godot/issues/16024

the solution has been presented that you must manually attach() and detach() the thread when created from GDScript (and it doesn't work from C# at present).

Thus the example solution by neikeq in the issue above is :

func _ready():
    t = Thread.new()
    t.start(self, "_thread_callback")

func _thread_callback():
    GodotSharp.attach_thread()
    # ...
    GodotSharp.detach_thread()

Which resolves my issue perfectly.

Edit: one final wrinkle is that I've found it won't work unless you're passing at least one parameter to the Thread.start()ed GDScript method, even if it's only a dummy. So the above example will need t.start(self, "threadcallback","dummy") and then func threadcallback(dummy):

Please log in or register to answer this question.

Welcome to Godot Engine Q&A, where you can ask questions and receive answers from other members of the community.

Please make sure to read Frequently asked questions and How to use this Q&A? before posting your first questions.
Social login is currently unavailable. If you've previously logged in with a Facebook or GitHub account, use the I forgot my password link in the login box to set a password for your account. If you still can't access your account, send an email to [email protected] with your username.