Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find out if I'm on the unity thread

How can I check if the thread I'm on is the Unity thread?

I tried capturing the threadId at constructor time, but somewhere along the lifetime of the program, the threadId moves.

In my project, some secondary thread processes need access to a newly created object.
I use the producer-consumer pattern so they can be created on the Unity thread. An object factory queues a request and on Update() the objects I requested are instantiated on the correct thread. Between Queued and Instantiated the factory method waits for an ObjectCreated event with an AutoResetEvent.

Now sometimes this factory will be called from the main thread and the AutoResetEvent will block its own thread. I also tried it the dirty way with

// First try on this thread
try
{
    return action();
}
catch (ArgumentException ex)
{
    Debug.Log("Tried on same thread, but failed. "+ex.Message);
}
PushToQueueAndWait(action);

But when unity throws the exception, caught or not, the program halts.

If I could check whether I'm on the correct thread, I could switch between queueing and just executing.

like image 797
Boris Callens Avatar asked Oct 19 '14 16:10

Boris Callens


People also ask

How do I use threads in Unity?

One thread runs at the start of a program by default. This is the “main thread”. The main thread creates new threads to handle tasks. These new threads run in parallel to one another, and usually synchronize their results with the main thread once completed.

Is Unity multithreaded or single threaded?

Unity side of things such as Animation, Rendering, Audio etc is multithreaded.

Is Unity thread safe?

You also need to remember that Unity API is not thread safe, so all calls to Unity API should be done from the main thread.

Does Coroutine run on main thread Unity?

Save this answer. Show activity on this post. Most of the Unity API can only be used on the Unity main-thread, StartCoroutine is one of those things. If you already are on a background thread you can also simply use UnityWebRequest.


1 Answers

I solved it by capturing the entire thread and then equalling it like so:

public void Start(){
    mainThread = System.Threading.Thread.CurrentThread;
}

bool isMainThread(){
    return mainThread.Equals(System.Threading.Thread.CurrentThread);
}

Related: http://answers.unity3d.com/questions/62631/i-wonder-about-thread-id-plz-answer-me.html

like image 94
Boris Callens Avatar answered Oct 15 '22 00:10

Boris Callens