读书人

pthread_create() 异常

发布时间: 2012-06-25 18:37:39 作者: rapoo

pthread_create() 错误
代码如下:

#include<pthread.h>
#include<iostream>

using namespace std;

class CThread
{
private:
pthread_t m_ThreadID;
int m_ThreadState; //the state of the thread



public:
CThread();
virtual ~CThread(){}

void Run();
void* ThreadFunction(void*); //调用函数run()
void Start()
{
pthread_create(&m_ThreadID,NULL,ThreadFunction,NULL);
} //Start to execute the thread 线程的执行入口,其调用ThreadFunction()函数,
int GetThreadState(void){return m_ThreadState;}
int GetThreadID(void){return m_ThreadID;}

};

CThread::CThread()
{
m_ThreadID = 0;
m_ThreadState = 0;
Start();
}



void* CThread::ThreadFunction(void*)
{
Run();
}

void CThread::Run()
{
cout<<"i am a thread~~~~~~~";
}

int main()
{
CThread thrd1;
return 0;

}
编译时出现一下错误:testcl1.cpp: In member function ‘void CThread::Start()’:
testcl1.cpp:22: error: argument of type ‘void* (CThread::)(void*)’ does not match ‘void* (*)(void*)’


[解决办法]
void* ThreadFunction(void*) 表面上只有一个void*的参数,实际上因为它是类的成员函数,所以它还有一个this指针的参数。所以提示pthread_create()第三个参数不匹配。
所以要在ThreadFunction(void*) 前加static,使之变成静态的,就没有this指针来碍事了
但是用了static之后 ThreadFunction()内部就不能调用非静态的run了,所以要把this指针作为ThreadFunction的参数传递进去
pthread_create(&m_ThreadID,NULL,ThreadFunction,NULL);
改为
pthread_create(&m_ThreadID,NULL,ThreadFunction,this);

void* CThread::ThreadFunction(void*)
{
Run();
}改为
void* CThread::ThreadFunction(void* par)
{
((CThread*)par)->Run();
}

[解决办法]
线程的入口函数可以是全局的,或者类静态成员函数。

读书人网 >C++

热点推荐