问题现象:
C++中创建线程,但在线程函数中无法使用同类下的private变量与函数。
问题分析:
通过
int pthread_create(pthread_t *thread,
const pthread_attr_t *attr,
void *(*start_routine) (void *),
void *arg);
创建线程,由于要求线程运行函数是static(上述第三个参数),导致在此函数中无法调用同类中的private变量与函数。
问题处理:
通过传参的方式,将所属类指针传入线程函数。
class Socket_base
{
private:
int m_abc;
static void* SocketServer(void* arg);
public:
Socket_base();
~Socket_base();
int SocketInitThread(void);
int SocketABC(void);
};
// use below struct for SocketServer(void* arg) can use the private para
struct PthreadParams
{
Socket_base* pThis;
/* other paras*/
};
通过PthreadParams *arg将类指针传入线程函数:
int Socket_base::SocketInitThread(void)
{
PthreadParams *arg = new PthreadParams();
arg->pThis = this;
int ret = pthread_create(&m_socketThread, NULL, SocketServer, (void*)arg);
if (ret != 0)
{
DEBUG_ERR(PROCESS_NAME) << "can't create socket thread: " << strerror(ret);
return EXTERN_FAIL;
}
return EXTERN_SUCCESS;
}
线程函数中指针的获取:
void* Socket_base::SocketServer(void* arg)
{
PthreadParams* arg0 = (PthreadParams*)arg;
Socket_base* pThis = arg0->pThis;
线程函数中private变量及函数的调用:
pThis->abc = 0;
pThis->SocketABC();