在C++的類中,普通成員函數不能作為pthread_create的線程函數,如果要作為pthread_create中的線程函數,必須是static !
在C語言中,我們使用pthread_create創建線程,線程函數是一個全局函數,所以在C++中,創建線程時,也應該使用一個全局函數。static定義的類的成員函數就是一個全局函數。
例如:
------------- cut here start -------------
#include <pthread.h>
class Thread
{
private:
pthread_t pid;
private:
static void * start_thread(void *arg); //靜態成員函數
public:
int start();
virtual void run() = 0;//基類中的虛函數要么實現,要么是純虛函數(絕對不允許聲明不實現,也不純虛)
};
int Thread::start()
{
if(pthread_create(&pid,NULL,start_thread,(void *)this) != 0) //創建一個線程(必須是全局函數)
{
return -1;
}
return 0;
}
void* Thread::start_thread(void *arg) //靜態成員函數只能訪問靜態變量或靜態函數,通過傳遞this指針進行調用
{
Thread *ptr = (Thread *)arg;
ptr->run();
return 0; //線程的實體是run
}
------------- cut here end -------------
#include <unistd.h>
#include <stdio.h>
#include "thread.h"
#include <stdlib.h>
class MyThread:public Thread
{
public:
void run();
};
void MyThread::run()
{
printf("hello world\n");
}
int main(int argc,char *argv[])
{
MyThread test;
test.start();
printf("------------\n");
//test.run();
sleep(1);
return 0;
}
------------- cut here end -------------
./g++ thread.cpp -lpthread -o main
./main
