创建线程:
# include <pthread.h>
int pthread_create(pthread_t *tidp, const pthread_attr_t *attr, void *(*start_rtn), void *arg)
tidp:创建线程时返回线程id
attr:线程属性(通常为空)
start_rtn:线程要执行的函数
arg:start_rtn的参数
返回值:创建成功就返回0,否则为非0;
编译
因为pthread的库不是linux系统的库,所以在进行编译的时候要加上
-lpthread
# gcc filename -lpthread
下面是一些例子:
1、thread_create.c
# include <stdio.h>
# include <pthread.h>
void *mythread1(void)
{
int i;
for(i=0; i<3; i++)
{
printf("this is the first pthread.\n");
sleep(1);
}
}
void *mythread2(void)
{
int i;
for(i=0; i<3; i++)
{
printf("this is the second pthread\n");
sleep(1);
}
}
int main(void)
{
int i = 0, ret = 0;
pthread_t id1, id2;
ret = pthread_create(&id1, NULL, (void *)mythread1, NULL);//创建线程1
if(ret)
{
printf("create pthread error\n");
return 1;
}
ret = pthread_create(&id2, NULL, (void *)mythread2, NULL);//创建线程2
if(ret)
{
printf("create pthread error\n");
return 1;
}
pthread_join(id1, NULL); //阻塞父进程,直到线程退出程序
pthread_join(id2, NULL);
return 0;
}
运行结果:
[regry@campusnetwork test]$ ./thread_create
this is the first pthread.
this is the second pthread
this is the first pthread.
this is the second pthread
this is the first pthread.
this is the second pthread
2、thread_int.c
# include <stdio.h>
# include <pthre