创建线程
函数定义
#include <pthread.h>
int pthread_create(pthread_t *restrict tidp,
const pthread_attr_t *restrict attr,
void *(*start_rtn)(void *), void *restrict arg);
返回值
成功返回0,失败返回错误编号。
参数
- tidp:线程id;
- attr:线程属性(通常为空);
- start_rtn:线程要执行的函数,是一个函数指针;
- arg:start_rtn的参数;
注意:因为pthread的库不是linux系统的库,所以在进行编译时要加上 -lpthread,格式如下:
gcc filename -lpthread
示例
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
void *testThread1(void)
{
for(int i = 0; i < 5; i++)
{
printf("create 1st thread!\n");
sleep(1);
}
}
void *testThread2(void)
{
for(int i = 0; i < 5; i++)
{
printf("create 2st thread!\n");
sleep(2);
}
}
int main()
{
int ret = 0;
pthread_t id1, id2;
ret = pthread_create(&id1, NULL, (void*)testThread1, NULL);
if(ret != 0)
{
printf("create thread1 error!\n");
return -1;
}
ret = pthread_join(id1, NULL);
if (ret != 0)
{
printf("join thread1 error\n");
return -1;
}
ret = pthread_create(&id2, NULL, (void*)testThread2, NULL);
if(ret != 0)
{
printf("create thread2 error!\n");
return -1;
}
ret = pthread_join(id2, NULL);
if (ret != 0)
{
printf("join thread2 error\n");
return -1;
}
return 0;
}
编译运行:
[root@192 pthread]# gcc -lpthread pthread_create.c -o pthread_create
[root@192 pthread]# ./pthread_create
create 1st thread!
create 1st thread!
create 1st thread!
create 1st thread!
create 1st thread!
create 2st thread!
create 2st thread!
create 2st thread!
create 2st thread!
create 2st thread!
[root@192 pthread]#