线程间通讯 [英] Interthread communication

查看:65
本文介绍了线程间通讯的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下问题与统一游戏引擎有关,但可能与任何试图将数据发送到主线程(例如UI线程)的程序有关.

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.

我正在一个单独的线程上处理一些数据(位置数据是从套接字异步读取的).但是,我需要对主线程上的数据进行操作(游戏对象的转换只能从主线程访问).我想到的方法是创建一个线程安全的队列并遵循生产者-消费者模式.线程将把位置数据排入队列,而主线程将使数据出队并对其执行操作. *注意:在Unity中,我无权访问System.Windows.Threading命名空间,因此无法使用Dispatcher.另外,它需要.Net 3.5,所以我也不能使用Collections.Concurrent名称空间.

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.

有更好的方法吗?

如果没有,什么是在数据排队时通知主线程的最佳方法?轮询似乎效率低下,但我想不出任何办法.

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..

谢谢.

推荐答案

这是一种完全可行的线程化方法.您可能知道,计算机硬件中轮询的替代方法是中断的概念.

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.

您将如何在多线程高级计算机程序中模拟中断?很难说-您的更改线程必须通知UI线程嘿,我准备好了",而​​不是不断地检查UI线程.这确实需要某种消息传递-可能不可行.

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.

这篇关于线程间通讯的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆