pthread_create(pthread_t handle, NULL, Thread_Main, parameter)
需要引用 libpthread.so
函数简介
pthread_create是UNIX环境创建线程函数
头文件
#include
函数声明
int pthread_create(pthread_t *restrict tidp,const pthread_attr_t *restrict_attr,void*(*start_rtn)(void*),void *restrict arg);
返回值
若成功则返回0,否则返回出错编号
参数
第一个参数为指向线程标识符的指针。
第二个参数用来设置线程属性。
第三个参数是线程运行函数的地址。
最后一个参数是运行函数的参数。
注意
在编译时注意加上-lpthread参数,以调用静态链接库。因为pthread并非Linux系统的默认库。
pthread_join函数
函数简介
函数pthread_join用来等待一个线程的结束。
函数原型为:
extern int pthread_join __P (pthread_t __th, void **__thread_return);
参数:
第一个参数为被等待的线程标识符
第二个参数为一个用户定义的指针,它可以用来存储被等待线程的返回值。
注意
这个函数是一个线程阻塞的函数,调用它的函数将一直等待到被等待的线程结束为止,当函数返回时,被等待线程的资源被收回。如果执行成功,将返回0,如果失败则返回一个错误号。
---------------------------------------------------------------
#include
#include
// linux API / pthread
#include
#include
struct ThreadParam
{
int id;
int max;
};
// 线程入口函数
void* Thread_Main(void* context)
{
ThreadParam* p = (ThreadParam*) context;
for(int i=0; imax; i++)
{
printf("thread: %d, count: %d\n", p->id, i);
sleep(1);
}
free(p);
printf("thread : %d exit . \n");
return NULL;
}
int main()
{
// 创建线程(同时启动线程)
pthread_t h1, h2;
// 创建第1个线程
ThreadParam* p1 = (ThreadParam*) malloc(sizeof(ThreadParam));
p1->id = 1;
p1->max = 10;
if(pthread_create(&h1, NULL, Thread_Main, p1) < 0)
{
printf("failed to create thread!\n");
return -1;
}
// 创建第2个线程
ThreadParam* p2 = (ThreadParam*) malloc(sizeof(ThreadParam));
p2->id = 2;
p2->max = 20;
if(pthread_create(&h2, NULL, Thread_Main, p2) < 0)
{
printf("failed to create thread!\n");
return -1;
}
pthread_join(h1, NULL); //等待子线程结束;
pthread_join(h2, NULL); //等待子线程结束;
printf("main exit.\n");
return 0;
}
编译: g++ thread.cpp -lpthread-o thread