1、函数原型
int pthread_creat(pthread_t *pid, const pthread_attr_t *attr,void *(*start_routine)(void *),void *arg);
- pid:返回创建成功后的线程ID,unsigned int型变量;
- attr:设置线程属性,为NULL则为默认属性;
- start_routine:指向线程函数;
- arg:直线传递给线程的参数。
2、用法
(1)包含头文件 #include <pthread.h>
(2)编译连接添加 -lpthread
3、示例
示例1:不传参数
#include <pthread.h>
#include <stdio.h>
#include <unistd.h> //sleep
void thread_func(void)
{
int i;
for(i = 0; i < 3; i++){
printf("thread cur cnt:%d\n",i);
}
printf("thread_func exit\n");
return;
}
int main(int argc,char *argv[])
{
pthread_t thrid;
int ret;
ret = thread_creat(&thrid,NULL,(void *(*)(void *))thread_func,NULL);
if(ret){
printf("pthread creat error:%d\n",ret);
return -1;
}
sleep(1);
return 0;
}
sleep(1)让main等待1秒,让线程执行。
示例2:传递整形
#include <pthread.h>
#include <stdio.h>
#include <unistd.h> //sleep
void thread_func(void *arg)
{
int i;
int *ptr = (int*)arg;
int cnt = *ptr;
printf("thread cur cnt:%d\n",cnt);
printf("thread_func exit\n");
return;
}
int main(int argc,char *argv[])
{
pthread_t thrid;
int ret;
int n = 5;
ret = thread_creat(&thrid,NULL,(void *(*)(void *))thread_func,&n);
if(ret){
printf("pthread creat error:%d\n",ret);
return -1;
}
sleep(1);
return 0;
}