I wonder about thread id. Plz answer me.
Asked Answered
F

2

0

Hi, everyone. First of all, I'm so sorry that I can't speak English Well.

I wonder about thread id. Please look at codes below.

using UnityEngine; 
using System.Collections; 
using System.Threading; 

public class TestScript : MonoBehaviour { 

    void Start () { 
          Debug.Log("current thread id: " + Thread.CurrentThread.GetHashCode().ToString()); 
          (new Thread(thread_test)).Start(); 
    } 

    static void thread_test() 
    { 
          Debug.Log("created thread id: " + Thread.CurrentThread.GetHashCode().ToString()); 
    } 
}

And I got the result below with console panel.

current thread id: 1 
created thread id: 1 

I expected the result below.

current thread id: 1 
created thread id: 2 

Why is 'created thread id' 1? Why isn't it 2? Are 'current thread' and 'created thread' the same thread?

Please tell me about that.

Freeloader answered 6/6, 2023 at 2:0 Comment(2)

Same deal here, still. Utiny and/or Mono seem to be playing games with us regarding thread ids. I'm positive I'm on a different thread when I call this, yet I get a 1 too always no matter what. WTF??

Rosauraroscius

Seems I posted as a comment instead of an answer.. Just wanted to say my problem went away the moment I left the editor. It seems this behaviour only occurs inside the editor, not in a build. Kinda screwed for testing purposes, fortunately it's a non-issue for me now..

Rosauraroscius
C
0

You probably want Thread.CurrentThread.ManagedThreadId instead

GetHashCode isn't guaranteed to be unique

Coaming answered 5/5, 2011 at 4:47 Comment(2)

Thank you very much for your answer. But, I changed my codes with Thread.CurrentThread.ManagedThreadId instead GetHashCode. And I got the same result. I don't know why yet.

Freeloader

I'm seeing this, too. Even when I know I've got a second thread, Thread.CurrentThread.ManagedThreadId is returning 1, same as the first thread. Yet in the second thread, Unity then proceeds to bark at me if I so much as compare a MonoBehaviour reference to null. What's the deal? How can we tell when we're on the main thread, if Thread.CurrentThread.ManagedThreadId always returns 1?

Cleres
P
0

Yeah, I found the same issue. My work around it was to store the current thread object itself (instead of the id), and to compare the references, as below.

object.ReferenceEquals(System.Threading.Thread.CurrentThread, mainThreadObject)

I also check mainThreadObject.IsAlive, but it always is. Hope it helps.

Pathan answered 6/6, 2023 at 1:35 Comment(1)

That seems like a good solution. If you're only storing a reference to the main thread, there are no leaks to worry about, as that one is never going to go away anyway. I like it!

Cleres

© 2022 - 2024 — McMap. All rights reserved.