封装线程会产生问题
Encapsulating Threads creates problems
我的 pthread_t
线程有以下封装:
#include <pthread.h>
class Thread
{
public:
void run(const int);
static void *run_helper(void *);
bool startThread(int);
void joinThread();
pthread_t th;
};
其中run
是我的线程例程,run_helper
是下面的:
void *Thread::run_helper(int num)
{
return (Thread *)this->run(num);
}
我这样开始我的话题:
bool Thread::startThread(intptr_t arg)
{
return (pthread_create(&this->th, NULL, &run_helper(arg), (void *)(intptr_t)arg));
}
但是编译的时候出现如下错误:
error: lvalue required as unary ‘&’ operand
return (pthread_create(&this->th, NULL, &run_helper(arg), (void *)(intptr_t)arg));
error: ‘this’ is unavailable for static member functions
return (Thread *)this->run(num);
尽管尝试过,但我似乎无法使这种封装工作。
我认为您的问题可能具体是 &this->th
。 &
的优先级高于 ->
。也许试试 &(this->th)
.
对于第一个错误,您需要将第三个参数转换为 (void*(*)(void*))
并删除 &
(也许不需要转换)。
pthread_create(&this->th, NULL, (void*(*)(void*))run_helper(arg), (void *)(intptr_t)arg);
第二个错误,您试图在静态函数中使用指向 this
的指针,但该函数未在任何对象上调用,因此您不能在静态函数中使用 this
那样的功能。解决方案是将arg
转换为Thread*
,然后调用非静态run
函数。
我的 pthread_t
线程有以下封装:
#include <pthread.h>
class Thread
{
public:
void run(const int);
static void *run_helper(void *);
bool startThread(int);
void joinThread();
pthread_t th;
};
其中run
是我的线程例程,run_helper
是下面的:
void *Thread::run_helper(int num)
{
return (Thread *)this->run(num);
}
我这样开始我的话题:
bool Thread::startThread(intptr_t arg)
{
return (pthread_create(&this->th, NULL, &run_helper(arg), (void *)(intptr_t)arg));
}
但是编译的时候出现如下错误:
error: lvalue required as unary ‘&’ operand return (pthread_create(&this->th, NULL, &run_helper(arg), (void *)(intptr_t)arg));
error: ‘this’ is unavailable for static member functions return (Thread *)this->run(num);
尽管尝试过,但我似乎无法使这种封装工作。
我认为您的问题可能具体是 &this->th
。 &
的优先级高于 ->
。也许试试 &(this->th)
.
对于第一个错误,您需要将第三个参数转换为 (void*(*)(void*))
并删除 &
(也许不需要转换)。
pthread_create(&this->th, NULL, (void*(*)(void*))run_helper(arg), (void *)(intptr_t)arg);
第二个错误,您试图在静态函数中使用指向 this
的指针,但该函数未在任何对象上调用,因此您不能在静态函数中使用 this
那样的功能。解决方案是将arg
转换为Thread*
,然后调用非静态run
函数。