I see your id is Chinese so I’ll use Chinese to answer first and if you’re not please comment and I’ll translate to English
我想你说的应该是指“协程”机制,即比线程更加轻量的并行方案。但是很遗憾由于C++是一门非常底层的且非常重视效率的语言,因此并没有直接性的支持协程机制。你有以下选择:
使用线程或者TaskGraph作为并发方案。从而让任务可以并行化。具体可以参考:TaskGraph:https://docs.unrealengine.com/latest/INT/API/Developer/TaskGraph/index.html;线程:https://wiki.unrealengine.com/Multi-Threading:_How_to_Create_Threads_in_UE4
自己实现协程机制。这也有多种方法。一种简单的方法,是通过某些方式,将任务分配到每一个Tick中执行。这也是我很多时候在不希望延缓主线程的情况下,将任务后台执行的选择。虚幻引擎的地图载入也采用了类似的机制。
另外,你也可以参考Boost::Asio库,也提供了一个基于宏的协程实现。类似这样:
class talk_to_svr : public boost::enable_shared_from_this<talk_to_svr>, public coroutine, boost::noncopyable {
...
void step(const error_code & err = error_code(), size_t bytes = 0) {
reenter(this)
{
for (;;) {
yield async_write(sock_, write_buffer_, MEM_FN2(step,_1,_2) );
yield async_read_until( sock_, read_buffer_,"\n", MEM_FN2(step,_1,_2));
yield service.post( MEM_FN(on_answer_from_server));
}
}
}
};
很遗憾我自己没有研究Boost::Asio的协程实现。所以无法给出更多建议。