使用Pthreads API多线程
Pthreads是指POSIX标准(IEEE1003.1c),该标准定义了用于线程创建和同步的API,它是线程行为的规范,而不是实现。该规范可由操作系统设计人员以他们希望的任何方式实施。如下所示的C程序演示了基本的PthreadsAPI,该API用于构造多线程程序,该程序在单独的线程中计算非负整数的总和。单独的线程在Pthreads程序中的指定函数中开始执行。在下面的程序中,这是runner()方法。程序启动时,一个控制线程开始于main()。main()创建第二个线程,开始在runner()方法,经过一些初始化。两个线程共享全局数据总和。pthread.h头文件必须包含在所有Pthreads程序中。我们将创建的线程的标识符。每个线程中都有一组属性,包括堆栈大小和调度信息。线程的属性由pthreadattr_t_attr的声明表示。我们在函数调用pthreadattrinit(&attr)中设置属性。因为我们没有显式设置任何属性,所以我们使用提供的默认属性。使用pthreadcreate()函数调用,将创建单独的线程。为了传递线程标识符和线程的属性,我们还传递了runner()函数,新线程将开始执行。最后,我们传递了命令行argv[1]上提供的整数参数。此时,程序具有两个线程:初始(或父)线程main()和执行该runner()函数中求和操作的求和(或子)线程。该程序遵循fork-join策略:创建求和线程后,父线程将通过调用pthreadjoin()函数等待其终止。当调用函数pthreadexit()时,求和线程将终止。父线程将在返回求和线程后输出共享数据总和的值,
使用PthreadsAPI的多线程C程序
示例
#include<pthread.h>
#include<stdio.h>
int sum;
/* This ‘sum’ is shared by the thread(s) */
void *runner(void *param);
/* threads call this function */
int main(int argc, char *argv[]){
pthread t tid;
/* the thread identifier */
pthread attr t attr;
/* set of thread attributes */
if (argc != 2){
fprintf(stderr,"usage: a.out \n");
return -1;
}
if (atoi(argv[1]) < 0){
fprintf(stderr,"%d must be >= 0\n",atoi(argv[1])); return -1;
}
/* get the default attributes */
pthread attr init(&attr);
/* create the thread */
pthread create(&tid,&attr,runner,argv[1]);
/* wait for the thread to exit */
pthread join(tid,NULL);
printf("sum = %d\n",sum);
}
/* The thread will begin handle in this function */
void *runner(void *param){
int i, upper = atoi(param);
sum = 0;
for (i = 1; i <= upper; i++)
sum += i;
pthread exit(0);
}