Interthread communication
Asked Answered
R

2

2

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.

Reptilian answered 22/1, 2013 at 14:23 Comment(1)
The unity tag is for Microsoft Unity. Please don't misuse it.Tingaling
H
2

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.

Haifa answered 22/1, 2013 at 14:29 Comment(0)
O
1

May be this question 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.

Oreste answered 22/1, 2013 at 14:33 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.