Pthread是由POSIX标准(IEEE 1003.1c)为线程创建和同步而定义的API,它是线程行为的规范,而不是实现。
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
int sum; /* this data is shared by the thread(s) */
void *runner(void *param); /* the thread */
int main(int argc, char *argv[])
{
pthread_t tid; /* the thread identifier */
pthread_attr_t attr; /* set of attributes for the thread */
if (argc != 2) {
fprintf(stderr,"usage: a.out <integer value>\n");
/*exit(1);*/
return -1;
}
if (atoi(argv[1]) < 0) {
fprintf(stderr,"Argument %d must be non-negative\n",atoi(argv[1]));
/*exit(1);*/
return -1;
}
/* get the default attributes */
pthread_attr_init(&attr);
/* create the thread */
pthread_create(&tid,&attr,runner,argv[1]);
/* now wait for the thread to exit */
pthread_join(tid,NULL);
printf("sum = %d\n",sum);
}
/**
* The thread will begin control in this function
*/
void *runner(void *param)
{
int i, upper = atoi(param);
sum = 0;
if (upper > 0) {
for (i = 1; i <= upper; i++)
sum += i;
}
pthread_exit(0);
}
在Pthread中,单独的线程在指定的函数中开始执行。在上面的代码中,是在runner()函数。
当程序运行时,单独的线程运行在main()函数,在初始化之后,main()创建了第二个线程,并在runner()函数中开始控制。两个线程共修昂全局数据sum。
- 所有的Pthread程序必须包含pthread.h头文件。
- pthread_t tid 是我们所创建的线程的标识符。
- 每个线程包括一些列的属性,包括栈大小以及调度信息。pthread_attr t attr声明代表的是线程的属性
- 通过pthread_attr_init(&attr)方法,来设置属性(第六章探讨又Pthread API提供的调度信息)
- 通过pthread_create()来创建新的线程,除了传递线程标识符以及线程属性集之外,我们还需要传递新的线程开始运行所在的函数的名称----------本例中指的是runner()函数。最后,传递的是一个integer参数,这个参数是由命令行传递进来的,即argv[1]
此时,程序有两个线程:在main()函数种的初始(或者可以称为父)线程以及在runner()函数上执行计算操作的计算(或者可以称为子)线程。
这个程序遵循fork-join策略,福线程通过pthread_join(),等待子线程的终止。
一旦子线程终止,父线程打印子线程的计算结果,即共享数据sum.
这个示例程序只创建一个线程。随着多核系统的主导地位,编写包含多个线程的程序变得越来越普遍。使用pthread_join()函数在多个线程上执行等待的一个简单方法是将该操作封装在一个简单的for循环中。例如,您可以使用下面的Pthread代码连接10个线程。
#define NUM THREADS 10
/* an array of threads to be joined upon */
pthread t workers[NUM THREADS];
for (int i = 0; i < NUM THREADS; i++)
pthread join(workers[i], NULL);