[英]C++ Thread in member function
如何在成員函數中使用線程在Windows中為C ++調用成員函數? 如果是,該如何實施? 這是樣本
void Class::fun_1(void){
_beginthread(fun_2, 0, NULL); //This is the error line :: function call missing argument list; use '&Class::fun_2' to create a pointer to member
}
void Class::fun_2(void){
printf("hello");
}
謝謝
這里實際上存在多個問題:
_beginthread()
函數的例程傳遞。 該函數需要一個指向全局或靜態函數的指針。 &
獲取指向該成員的指針(編譯器在此向您抱怨)。 因為您不能將成員函數指針傳遞給_beginthread()
,所以需要創建一個包裝器全局或靜態函數以使其起作用。 這是實現這一目標的一種方法:
class MyClass
{
public:
void fun_1()
{
_beginthread(&MyClass::fun_2_wrapper, 0, static_cast<void*>(this));
}
private:
void fun_2()
{
printf("hello");
}
static void __cdecl fun_2_wrapper(void* o)
{
static_cast<MyClass*>(o)->fun_2();
}
};
當然,您需要以某種方式保證只要fun_2()
正在運行, MyClass
對象仍將存在,否則會發生不好的事情。 如果您不必擔心,可以考慮使用Boost.Thread ,它基本上可以完成此任務,並且為您提供更多幫助。
通常的方法是使用靜態成員函數,該成員函數使用指向原始對象的空指針來調用該成員函數。
class Class
{
public:
void fun_1(void)
{
_beginthread( &Class::static_fun_2, 0, this );
}
void fun_2(void)
{
printf("hello");
}
private:
static void static_fun_2( void * args )
{
static_cast<Class*>(args)->fun_2();
}
};
但是,如果您開始需要將參數傳遞給這些函數,則事情會變得有些復雜。 我會看看使用boost :: thread和boost :: bind而不是自己動手。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.