- Home /
Unity interthread communication.
Hey all,
I am processing some data on a separate thread (position data 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 themain 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. 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, is continously checking in a coroutine and yield return 0 if there's no data be my best option?
Thanks in advance.
Answer by musselmc · Jan 29, 2013 at 03:42 PM
Just an FYI, I ended up creating a thread-safe queue and pumped the socket data into it on one thread while removing and acting on the data on the main thread. - http://stackoverflow.com/questions/14460763/interthread-communication
Hey there's an example of my version of that on Unity Gems the article on threads.
I pass a system action to the main thread and then call that - it's a nice coding pattern as it keeps your logic together.
Cool, definitely something I'll look at more closely if I find the time to refactor or run into performance problems.
Cool. It's the same technique you ae using but with code and data inside a lamda ins$$anonymous$$d of just data.