最适合使用线程的实现以下功能的应用:
线程系统的三个基本要素:执行环境、调度和同步。
pthread_join的应用
线程终止
两种方式终止线程。
第一通过return从线程函数返回,
第二种通过调用pthread_exit()函数使线程退出。
需要注意的地方:一是,主线程中如果从main函数返回或是调用了exit函数退出主线程,则整个进程终止,此时所有的其他线程也将终止。另一种是,如果主线程调用pthread_exit函数,则仅仅是主线程消亡,进程不会结束,其他线程也不会结束,知道所有的线程都结束时,进程才结束。
线程属性
1 /* man pthread_attr_init */
2 typedef struct
3 {
4 int detachstate; //是否与其他线程脱离同步
5 int schedpolicy; //新线程的调度策略
6 struct sched_param schedparam; //运行优先级等
7 int inheritsched; //是否继承调用者线程的值
8 int scope; //线程竞争CPU的范围(优先级的范围)
9 size_t guardsize; //警戒堆栈的大小
10 int stackaddr_set; //堆栈地址集
11 void * stackaddr; //堆栈地址
12 size_t stacksize; //堆栈大小
13 } pthread_attr_t;
属性值不能直接设置,须使用相关函数进行操作,初始化的函数为pthread_attr_init,这个函数必须在pthread_create函数之前调用。
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <pthread.h>
void thread(void)
{
int i;
for(i = 0; i < 4; i++)
printf("This is a pthread.\n"), sleep(1);
}
int main(void)
{
pthread_t id;
int i, ret;
ret = pthread_create(&id, NULL, (void*)thread, NULL);
if(ret != 0) {
printf("Create pthread error!\n");
exit(EXIT_FAILURE);
}
for(i = 0; i < 3; i++)
printf("This is the main process.\n"), sleep(1);
pthread_join(id, NULL);
return 0;
}
执行结果如下: