Use Unity API from another Thread or call a function in the main Thread

前端 未结 4 1447
醉梦人生
醉梦人生 2020-11-21 22:19

My problem is I try to use Unity socket to implement something. Each time, when I get a new message I need to update it to the updattext (it is a Unity Text). However, When

4条回答
  •  不知归路
    2020-11-21 22:45

    Much of the writing about threads in Unity is incorrect.

    How so?

    Unity is, of course, totally frame-based.

    When you work in a frame-based system, threading issues are completely different.

    Threading issues on a frame-based system are completely different. (In fact, often much easier to deal with.)

    Let's say you have a Unity thermometer display that shows some value

    Thermo.cs
    

    So it will have a function which is called in Update, like

    func void ShowThermoValue(float fraction) {
       display code to show the current thermometer value
    }
    

    Recall that the "Update" function in Unity simply means "run this once each frame".

    That only runs once per frame, and that's that.

    (Naturally, it runs only on the "main thread". There's nothing else in Unity! There's just ... "the Unity thread"!)

    Somewhere else, perhaps in "IncomingData.cs", you will have a function which handles the concept "a new value has arrived":

    [MonoPInvokeCallback(typeof(ipDel))]
    public static void NewValueArrives(float f) {
    
        ... ???
    }
    

    Note that, of course, that is a class function! What else can it be?

    You can't "reach in to" a normal Unity function. (Such as ShowThermoValue.) That would be meaningless - it's just a function which runs once each frame.Footnote 1

    Let's say: values arrive very frequently and irregularly.

    Image you have some sort of scientific devices (perhaps IR thermometers) connected connected to a rack of PCs

    Those electronic devices deliver new "temperature" values very often. Let's say dozens of times per frame.

    So, "NewValueArrives" is being called 100s of times a second.

    So what do you do with the values?

    It could not be simpler.

    From the arriving-values thread, all you do is ................. wait for it ............. set a variable in the component!!

    WTF? All you do is set a variable? That's it? How can it be that simple?

    This is one of those unusual situations:

    1. Much of the writing on threads in Unity is, simply, completely hopeless.

    2. Surprisingly, the actual approach is extremely simple.

    3. It's so simple you may think you are doing something wrong!!

    So have the variable ...

    [System.Nonserialized] public float latestValue;
    

    Set it from the "arriving thread" ...

    [MonoPInvokeCallback(typeof(ipDel))]
    public static void NewValueArrives(float f) {
    
        ThisScript.runningInstance.latestValue = f; // done
    }
    

    Honestly that's it.

    Essentially, to be the world's greatest expert at "threading in Unity" - which is, obviously, frame-based - there's nothing more to do than the above.

    And whenever ShowThermoValue is called each frame ...................... simply display that value!

    Really, that's it!

    [System.Nonserialized] public float latestValue;
    func void ShowThermoValue() { // note NO arguments here!
       display code, draws a thermometer
       thermo height = latestValue
    }
    

    You're simply displaying the "latest" value.

    latestValue may have been set once, twice, ten times, or a hundred times that frame ............ but, you simply display whatever is the value when ShowThermoValue runs that frame!

    What else could you display?

    The thermometer is updating at 60fps on-screen so you display the latest value. Footnote 2

    It's actually that easy. It's just that easy. Surprising but true.


    #(Critical aside - don't forget that vector3, etc, are NOT Atomic in Unity/C#)

    As user @dymanoid has pointed out (read the important discussion below) it's critical to remember that while float is atomic in the Unity/C# milieu, anything else (say, Vector3 etc) IS NOT ATOMIC. Typically (as in the example here) you only pass floats around from calculations from, say, native plugins, thermometers etc. But it's essential to be aware that vectors and so on are NOT atomic.


    Sometimes experienced threading programmers get in a knot with a frame-based system, because: in a frame based system most of the problems caused by racetrack and locking issues ... do not exist conceptually.

    In a frame-based system, any game items should simply be displaying or behaving based on some "current value," which is set somewhere. If you have info arriving from other threads, just set those values - you're done.

    You can not meaningfully "talk to the main thread" in Unity because that main thread ............. is frame-based!

    Most locking, blocking and racetrack issues are non-existent in the frame-based paradigm because: if you set latestValue ten times, a million times, a billion times, in one particular frame .. what can you do? .. you can only display one value during that frame!

    Think of an old-fashioned plastic film. You literally just have ...... a frame, and that's it. If you set latestValue a trillion times in one particular frame, ShowThermoValue will simply display (for that 60th of a second) the one value it grabs when it is run.

    All you do is: leave information somewhere, which, the frame-paradigm system will utilize during that frame if it wants to.

    That's it in a nutshell.

    Thus, most "threading issues" disappear in Unity.

    All you can do from

    • other calculation threads or

    • from plugin threads,

    is just "drop-off values" which the game may use.

    That's it!

    Let's consider the question title...

    How do you "... call a function in the main Thread"

    This is completely meaningless. The "functions" in Unity are simply functions which the frame engine runs once per frame.

    You can't "call" anything in Unity. The frame engine runs a number of things (many things) once per frame.

    Note that indeed threads are totally irrelevant. If Unity ran with a billion threads, or with quantum computing, it would have no bearing on anything.

    You can't "call a function" in a frame-based system.

    Fortunately, the approach to take is dead simple, you just set values, which the frame-based functions can look at when they want! It's really that easy.


    Footnotes


    1 How could you? As a thought experiment, forget about the issue that you're on a different thread. ShowThermoValue is run once a frame by the frame engine. You can't "call" it in any meaningful way. Unlike in normal OO software, you cannot, say, instantiate an instance of the class (a Component?? meaningless) and run that function - that is completely meaningless.

    In "normal" threaded programming, threads can talk back and fore and so on, and in doing so you have concerns about locking, racetrack and so on. But that is all meaningless in an ECS, frame-based, system. There is nothing to "talk to".

    Let's say that Unity was in fact multithreaded!!!! So the Unity guys have all of the engine running in a multithreaded manner. It wouldn't make any difference - you can not get "in to" ShowThermoValue in any meaningful way! It's a Component which the frame engine runs once a frame and that's that.

    So NewValueArrives is not anywhere - it's a class function!

    Let's answer the question in the headline:

    "Use Unity API from another Thread or call a function in the main Thread?"

    The concept is >> completely meaningless <<. Unity (like all game engines) is frame-based. There's no concept of "calling" a function on the main thread. To make an analogy: it would be like a cinematographer in the celluloid-film era asking how to "move" something actually on one of the frames.

    Of course that is meaningless. All you can do is change something for the next photo, the next frame.


    2 I refer to the "arriving-values thread" ... in fact! NewValueArrives may, or may not, run on the main thread!!!! It may run on the thread of the plugin, or on some other thread! It may actually be completely single-threaded by the time you deal with the NewValueArrives call! It just doesn't matter! What you do, and all you can do, in a frame-based paradigm, is, "leave laying around" information which Components such as ShowThermoValue, may use, as, they see fit.

提交回复
热议问题