参考:https://blog.csdn.net/chm880910/article/details/48377273
简单例子:
#include <stdio.h>
#include <pthread.h>
#include <iostream>
using namespace std;
//创建线程示例:
void* thread_1(void* args)
{
for( int i = 0;i < 3; i++ )
printf("This is a pthread.\n");
}
int test_thread_1()
{
pthread_t id=0;
int ret;
ret = pthread_create( &id, NULL, thread_1, NULL );
if ( ret!=0 ) {
printf ("Create pthread error!\n");
return 1;
}
for( int i = 0; i < 3; i++ )
printf("This is the main process.\n");
pthread_join(id,NULL);
return 0;
}
// 向线程执行函数 传入参数,以及返回线程执行函数的结果 示例:
void* thread_2( void *arg )
{
for (int i=0;i<5;i++)
{
printf( "This is a thread and arg[%d] = %d.\n",i, ((int*)arg)[i]);
((int*)arg)[i] += 1;//plus 1
}
return arg;
}
int test_thread_2()
{
pthread_t th=2;
int ret;
int arg[5] = {1,2,3,4,5};
int *thread_ret = NULL;
ret = pthread_create( &th, NULL, thread_2, arg );
if( ret != 0 ){
printf( "Create thread error!\n");
return -1;
}
printf( "This is the main process.\n" );
pthread_join( th, (void**)&thread_ret );
for (int i=0;i<5;i++)
{
printf( "thread_ret arg[%d] = %d.\n",i, ((int*)thread_ret)[i]);
}
return 0;
}
int main( int argc, char *argv[] )
{
test_thread_1();
test_thread_2();
return 0;
}
在类中,将类成员函数传入pthread_create,创建线程,示例:
需将线程执行函数定义成静态成员函数;
如需访问类的非static数据成员, 可将this指针作为参数传递给静态成员函数,这样可以通过该this指针访问非static数据成员;
如果还需要向静态函数中传递我自己需要的参数,可将this指针和需要的参数作为一个结构体一起传给静态函数;
具体请看下面示例代码:
//在类中pthread_create创建线程模板:
class A;
struct ARG
{
A* pThis;
string var;
};
class A
{
public:
A();
~A();
static void* thread(void* args);
void excute();
private:
int iCount;
};
A::A()
{
iCount = 10;
}
A::~A()
{
}
void* A::thread(void* args)
{
ARG *arg = (ARG*)args;
A* pThis = arg->pThis;
string var = arg->var;
cout<<"传入进来的参数var: "<<var<<endl;
cout<<"用static线程函数调用私有变量: "<<pThis->iCount<<endl;
}
void A::excute()
{
int error;
pthread_t thread_id;
ARG *arg = new ARG();
arg->pThis = this;
arg->var = "abc";
error = pthread_create(&thread_id, NULL, thread, (void*)arg);
if (error == 0)
{
cout<<"线程创建成功"<<endl;
pthread_join(thread_id, NULL);
}
}
int test_thread_3()
{
A a;
a.excute();
return 0;
}