在直接问你我的问题之前,我将描述我的问题的性质。 我正在使用 C++/OpenGL 和 GLFW 库编写 2D 模拟。而且我需要正确管理很多线程。在 GLFW 中我们必须调用函数: thread = glfwCreateThread(ThreadFunc, NULL); (第一个参数是执行线程的函数,第二个参数代表这个函数的参数)。 而 glfwCreateThread,每次都必须调用! (即:在每个周期中)。这种工作方式并没有真正帮助我,因为它打破了我构建代码的方式,因为我需要在主循环范围之外创建线程。所以我正在创建一个 ThreadManager 类,它将具有以下原型(prototype):
class ThreadManager {
public:
ThreadManager();
void AddThread(void*, void GLFWCALL (*pt2Func)(void*));
void DeleteThread(void GLFWCALL (*pt2Func)(void*));
void ExecuteAllThreads();
private:
vector<void GLFWCALL (*pt2Func)(void*)> list_functions;
// some attributs
};
例如,如果我想添加一个特定的线程,我只需要使用特定的参数和特定的函数调用 AddThread。目标只是能够调用:ExecuteAllThreads();在主循环范围内。但是为此我需要有类似的东西:
void ExecuteAllThreads() {
vector<void GLFWCALL (*pt2Func)(void*)>::const_iterator iter_end = list_functions.end();
for(vector<void GLFWCALL (*pt2Func)(void*)>::const_iterator iter = list_functions.begin();
iter != iter_end; ++iter) {
thread = glfwCreateThread(&(iter*), param);
}
}
在 AddThread 中,我只需将 pt2Func 引用的函数添加到 vector :list_functions。
好吧,这是我想做的事情的总体思路..这是正确的方法吗?你有更好的主意吗?真的,该怎么做? (我的意思是问题出在语法上,我不知道该怎么做)。
谢谢!
最佳答案
您需要在每个模拟周期中创建线程吗?这听起来很可疑。创建您的线程一次,然后重复使用它们。
创建线程并不是一项成本低廉的操作。您绝对不想在每个迭代步骤中都这样做。
如果可能,我建议您改用 Boost.Thread 作为线程,以提供类型安全和其他方便的功能。在不放弃类型安全和使用原始 C API 的情况下,线程已经足够复杂了。
就是说,您的要求是可能的,尽管它变得困惑。首先,您还需要存储函数的参数,因此您的类看起来像这样:
class ThreadManager {
public:
typedef void GLFWCALL (*pt2Func)(void*); // Just a convenience typedef
typedef std::vector<std::pair<pt2Func, void*> > func_vector;
ThreadManager();
void AddThread(void*, pt2Func);
void DeleteThread(pt2Func);
void ExecuteAllThreads();
private:
func_vector list_functions;
};
然后执行所有线程:
void ExecuteAllThreads() {
func_vector::const_iterator iter_end = list_functions.end();
for(func_vector::const_iterator iter = list_functions.begin();
iter != iter_end; ++iter) {
thread = glfwCreateThread(iter->first, iter->second);
}
}
当然,在 AddThread 中,您必须向 vector 添加一对函数指针和参数。
请注意,Boost.Thread 可以更清晰地解决大部分问题,因为它期望线程是一个仿函数(它可以保持状态,因此不需要显式参数)。
你的线程函数可以这样定义:
class MyThread {
MyThread(/* Pass whatever arguments you want in the constructor, and store them in the object as members */);
void operator()() {
// The actual thread function
}
};
并且由于 operator() 不带任何参数,因此启动线程变得更加简单。
关于c++ - 如何维护 C++/STL 中的函数列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/786131/