【发布时间】:2014-08-27 02:05:20
【问题描述】:
所以我想弄清楚你是否可以使用奇怪的重复模板模式来绕过 pthread 与类方法一起使用的限制,甚至通过做一些类似的事情来创建类。
template <class T>
class thread_helper
{
static void* create(void *input)
{
T * output=new T;
return static_cast<void*>(output);
}
static void* using(void *input)
{
T::use(input);
}
};
class user : public thread_helper<user>
{
void method(int x)
{
//does something
}
static void use(void* input)
{
this->method(static_cast<int>(input));
}
};
然后你可以使用 pthread 来调用类创建使用
pthread_create(thread_variable, NULL, thread_helper::create<some_class>, void);
和另一个电话
pthread_create(thread_variable, NULL, user::using(), void);
注意:上面的代码有很多错误。请不要为了他们撕毁我。我真的只是想描绘我正在尝试做的事情。我也在尝试找出是否有更好的方法来执行此操作。
另外,第二个pthread_create 方法真的很有必要,我不能只使用构造函数吗?
【问题讨论】:
-
using 是保留字。无论如何,典型的范例是将您的类实例地址转换为 void* 并将其作为线程参数传递给线程过程,该线程过程将其转换回相同的指针。如果您有 C++11,请考虑使用 std::thread。
-
"如果有更好的方法来执行这个操作" - 在单独的线程中运行构造函数通常不是很有用,除非你有一些同步的方式来访问对象 - 我建议你阅读在
std::future等人上。 -
@TonyD 我检查了 std::future。这让我很恼火,我不能在这个项目中使用新标准。我也同意你不确定构造函数部分是否真的需要线程化。无论如何,我最终得到了一个代码,它可以工作,但它有大量的样板代码。