- 创建线程
创建线程的函数是pthread_create,具体定义如下:
#include <pthread.h>
int pthread_create(pthread_t *thread, // 新创建的线程ID
const pthread_attr_t *attr, // 线程属性
void *(*start_routine) (void *), // 新创建的线程从start_routine开始执行
void *arg); // 执行函数的参数
创建线程函数使用示例:
/* example.c*/
#include <stdio.h>
#include <pthread.h>
#include <unistd.h>
void thread()
{
int i = 0;
for(i=0;i<3;i++)
{
printf("This is the new pthread (%d).\n", i);
sleep(1);
}
}
int main(int argc, char *argv[])
{
pthread_t id;
int ret = 0;
ret=pthread_create(&id, NULL, (void *) thread, NULL);
if(ret!=0)
{
printf ("Create pthread error!\n");
return 0;
}
printf("This is the main thread.\n");
return 0;
}
使用如下命令编译:gcc -o newthread newthread.c
发现编译不通过,报错如下:
[yuanping@Linux C]$ gcc -o newthread -g newthread.c
/tmp/ccKagF7L.o: In function `main':
newthread.c:(.text+0x7c): undefined reference to `pthread_create'
newthread.c:(.text+0xe5): undefined reference to `pthread_join'
collect2: ld returned 1 exit status
[yuanping@Linux C]$
报这个错误的原因是:pthread库不是linux默认的库,所以在编译时候需要指明libpthread.a库。
解决方法:在编译时,加上-lpthread参数。
使用如下命令编译成功:
gcc -lpthread -o newthread -g newthread.c
执行结果:
[yuanping@Linux C]$ newthread
This is the main thread.
[yuanping@Linux C]$
上述结果并非预期的结果,预期的结果应该新创建的线程也打印 This is the new thread.
出现此问题的原因是主线程没有等待子线程正常退出,主线程运行结束退出时,所有的子线程都退出了。下面介绍通过pthread_join函数等待子线程运行结束。
- 等待线程退出
#include <pthread.h>
int pthread_join(pthread_t thread, // 等待退出的线程ID
void **retval); // 获取线程退出时的返回值
对前面的程序进行改进,添加pthread_join(id, NULL);如下:
/* example.c*/
#include <stdio.h>
#include <pthread.h>
#include <unistd.h>
void thread()
{
int i = 0;
for(i=0;i<3;i++)
{
printf("This is the new pthread (%d).\n", i);
sleep(1);
}
}
int main(int argc, char *argv[])
{
pthread_t id;
int ret = 0;
ret=pthread_create(&id, NULL, (void *) thread, NULL);
if(ret!=0)
{
printf ("Create pthread error!\n");
return 0;
}
printf("This is the main thread.\n");
pthread_join(id, NULL);
return 0;
}
编译运行结果如下:[yuanping@Linux C]$ gcc -lpthread -o newthread -g newthread.c
[yuanping@Linux C]$ newthread
This is the main thread.
[yuanping@Linux C]$ gcc -lpthread -o newthread -g newthread.c
[yuanping@Linux C]$ newthread
This is the main thread.
This is the new pthread (0).
This is the new pthread (1).
This is the new pthread (2).
[yuanping@Linux C]$
运行结果与预期的结果一致。