函数pthread_create
作用:创建线程
函数原型:
int pthread_create(pthread_t * tidp,const pthread_attr_t*attr,void*(*start_rtn)(void),void*arg)
参数:tidp:线程id
attr: 线程属性(通常为空)
start_rtn:线程要执行的函数
arg:start_rtn的参数
头文件:#include <pthread.h>
因为pthread的库不是linux系统的库,所以在进行编译的时候要加上-lpthread即 gcc filename -lpthread
如果进程中任何一个线程中调用exit或_exit,那么整个进程都会终止。线程的正常退出方式有:
(1) 线程从启动例程中返回
(2) 线程可以被另一个进程终止
(3) 线程自己调用pthread_exit函数
函数pthread_exit
函数功能:终止调用线程
函数原型: void pthread_exit(void * rval_ptr)
函数参数:Rval_ptr:线程退出返回值的指针
头文件:#include <pthread.h>
函数pthread_join
函数功能:阻塞调用线程,直到指定的线程终止。
函数原型:
int pthread_join(pthread_t tid,void **rval_ptr)
函数参数:Tid :等待退出的线程id
Rval_ptr:线程退出的返回值的指针
头文件:#include <pthread.h>
简单例子:
#include <stdio.h>
#include <pthread.h>
void *myThread1(void)
{
int i;
for (i=0; i<3; i++)
{
printf("This is the 1st pthread,created by zieckey.\n");
sleep(1);//Let this thread to sleep 1 second,and then continue to run
}
}
void *myThread2(void)
{
int i;
for (i=0; i<3; i++)
{
printf("This is the 2st pthread,created by zieckey.\n");
sleep(1);
}
}
int main()
{
int i=0, ret=0;
pthread_t id1,id2;
/*创建线程1*/
ret = pthread_create(&id1, NULL, (void*)myThread1, NULL);
if (ret)
{
printf("Create pthread error!\n");
return 1;
}
/*创建线程2*/
ret = pthread_create(&id2, NULL, (void*)myThread2, NULL);
if (ret)
{
printf("Create pthread error!\n");
return 1;
}
pthread_join(id1, NULL);
pthread_join(id2, NULL);
return 0;
}
#include <stdio.h>
#include <pthread.h>
#include <unistd.h>
struct menber
{
int a;
char *b;
}temp={8,"zieckey"};
void *create(void *arg)
{
printf("new thread ... \n");
return (void *)&temp;
}
int main(int argc,char *argv[])
{
int error;
pthread_t tid;
struct menber *c;
error = pthread_create(&tid, NULL, create, NULL);
if( error )
{
printf("new thread is not created ... \n");
return -1;
}
printf("main ... \n");
error = pthread_join(tid,(void *)&c);
if( error )
{
printf("new thread is not exit ... \n");
return -2;
}
printf("c->a = %d \n",c->a);
printf("c->b = %s \n",c->b);
sleep(1);
return 0;
}