具有多线程支持的 RenderClass,将函数调用推送到向量以在另一个线程上调用

RenderClass with Multithread-Support, push functioncalls to vector for invoking on another thread

本文关键字:向量 另一个 调用 线程 支持 多线程 RenderClass 函数调用      更新时间:2023-10-16

我正在尝试制作一个 RenderClass,其中 1 个函数从线程调用,该线程计算所有内容并将函数调用推送到向量,而另一个线程调用 RenderClass 的函数,然后调用在向量上推送的每个函数,这甚至可能吗? 此外,我的代码没有给我智能感知错误,而不仅仅是一些奇怪的 C3867 错误,我认为在尝试编译时没有意义。

我已经尝试过使用模板功能 比如删除渲染类::*函数

template<typename Function, typename ...ARGS>
void QueueRenderFunction(Function *function, ARGS... args)

但无法让它工作。

在这里,我测试了整个测试程序...

#include <Windows.h>
#include <iostream>
#include <functional>
#include <string>
#include <vector>
#include <mutex>
class Vector3 {
float x, y, z;
};
class RenderClass
{
public:
template<typename Function, typename ...ARGS>
void QueueRenderFunction(Function RenderClass::*function, ARGS... args)
{
_RenderList.push_back(std::forward<Function>(function, args...));
}
void CallRenderFunctions()
{
std::lock_guard<std::recursive_mutex> l(renderlist_mtx);
for (auto&& Function : RenderList)
Function();
}
//just as examplecode
void DRAWCIRCLE(Vector3 Position, float Range) {
std::cout << Range << std::endl;
}
void DRAWSTRING(Vector3 Position, std::string String) {
std::cout << String << std::endl;
}
void QueueDrawings() {
//begin new Renderlist
_RenderList.clear();
//some drawing calcs
//some Position
Vector3 Position;
QueueRenderFunction(DRAWCIRCLE, Position, 100.f);
QueueRenderFunction(DRAWSTRING, Position,"Name");
std::lock_guard<std::recursive_mutex> l(renderlist_mtx);
RenderList = _RenderList;
}
private:
std::recursive_mutex renderlist_mtx;
std::vector<std::function<void()>> RenderList;
std::vector<std::function<void()>> _RenderList;
};
RenderClass* Renderer = new RenderClass();
void Render() {
while (true)
{
Renderer->CallRenderFunctions();
std::this_thread::sleep_for(std::chrono::milliseconds(1));
}
}
int main() {
std::thread RenderThread(Render);
while (true)
{
Renderer->QueueDrawings();
std::this_thread::sleep_for(std::chrono::milliseconds(1));
}
return 0;
}

就像说我得到例如这个错误:

严重性代码说明项目文件行抑制状态 错误 C3867 "渲染类::D RAWCIRCLE":非标准语法;使用"&"创建指向成员的指针

并试图 &画圈 就在那时给了我

错误 C2276 '&':对绑定成员函数表达式执行非法操作

这就是让我说在我看来没有意义的原因

你的问题是你有一个std::vector<std::function<void()>>,这很好,但你需要添加一些增强。 std::bind 是你的朋友。

这段代码应该可以解决问题。

template<typename Function, typename ...ARGS>
void QueueRenderFunction(Function function, ARGS... args)
{
_RenderList.push_back(std::bind(function, args...));
}

您可能还希望将放入渲染列表中的函数定义为没有函数,并将本来可以作为参数传递的内容。

作为旁注,您可能希望使用RenderList.swap(_RenderList);来减少复制。