Interthread communication

China☆狼群 提交于 2019-12-23 02:59:13

问题


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.


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/14460763/interthread-communication

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!