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();
void Run();
static void* ThreadFunction(void* par); //调用函数run()
void Start()
{
cout<<"~~~~start~~~~"<<endl;
if( pthread_create(&m_ThreadID,NULL,ThreadFunction,this) == 0)
cout<<"~~~xianchengchuangjianchenggong!!!!!"<<endl;
} //Start to execute the thread 线程的执行入口,其调用ThreadFunction()函数,
int GetThreadState(void){return m_ThreadState;}
int GetThreadID(void){return m_ThreadID;}
~CThread(){}
};
CThread::CThread()
{
cout<<"~~~~gouzao~~~~"<<endl;
m_ThreadID = 0;
m_ThreadState = 0;
Start();
}
void* CThread::ThreadFunction(void* par)
{
cout<<"~~~~function~~~~"<<endl;
((CThread*)par)->Run();
}
void CThread::Run()
{
cout<<"i am a thread~~~~~~~";
}
int main()
{
cout<<"~~~~main~~~~"<<endl;
CThread thrd1;
cout<<"i am the main function!";
return 0;
}
问题:pthread_create()创建成功,但是他不执行ThreadFunction函数里的输出语句。
[解决办法]
main函数return 0前面加一句 Sleep(1000);
或者用waitforsingleobject(线程的句柄)函数 来等待辅助线程返回。(我只会用windows的线程函数)
原因是由于主线程已经结束,而辅助线程还没来得及执行那些输出语句,就被迫结束了。