The following question is about the unity game engine, but it could relate to any program trying to send data to a main thread, such as the UI thread.
I am processing some data on a separate thread (position data a read asyncrously from a socket). However, I need to act on this data on the main thread (a game object's transform can only be accessed from the main thread). The approach I have in mind is to create a thread-safe queue and follow the producer-consumer pattern. The thread would queue the position data and the main thread would deque the data and act on it. *Note: In Unity I do not have access to the System.Windows.Threading name space so I can not use Dispatcher. Also, it requires .Net 3.5 so I can't use the Collections.Concurrent name space either.
Is there a better approach?
If there isn't, what is the best way to inform the main thread when data is queued? It seems inefficient to poll, but I can't think of any way around it..
Thanks in advance.Answer1:
That is a totally viable approach to threading. As you probably know, the alternative to polling found in computer hardware is the concept of interrupts.
How would you simulate interrupts in a multithreaded high-level computer program? Hard to say - your thread that changes would have to notify the UI thread "hey I'm ready", rather than the UI thread checking constantly. This requires some sort of message passing, really - it may not be feasible.
That being said, the typical game-design approach is the "game loop" that does, essentially, poll. So there is no shame in that game - you just have to make sure it doesn't murder your performance.Answer2:
May be <a href="https://stackoverflow.com/questions/22356/cleanest-way-to-invoke-cross-thread-events" rel="nofollow">this question</a> has an answer for you.
However, polling a queue is a cleaner solution IMHO, and not so costly if done right and there are tons of examples in the Internet.