使用 Pthreads API 的多线程
Pthreads 指的是 POSIX 标准 (IEEE 1003.1c),它定义了用于线程创建和同步的 API,这是一个线程行为规范,而不是实现。操作系统设计人员可以根据需要以任何方式实现此规范。下面显示的 C 程序演示了用于构建多线程程序的基本 Pthreads API,该程序在单独的线程中计算非负整数的总和。单独的线程在 Pthreads 程序中的指定函数中开始执行。在下面的程序中,这是 runner() 函数。程序开始时,一个单线程控制在 main() 中开始。main() 创建一个第二个线程,该线程在一些初始化后在 runner() 函数中开始控制。这两个线程共享全局数据 sum。所有 Pthreads 程序都必须包含 pthread.h 头文件。我们将创建的线程的标识符。每个线程中都有一组属性,包括堆栈大小和调度信息。线程的属性由 pthread_attr_t attr 的声明表示。我们在函数调用 pthread_attr_init(&attr) 中设置属性。因为我们没有显式设置任何属性,所以我们使用提供的默认属性。通过 pthread_create() 函数调用,创建单独的线程。传递线程标识符和线程的属性,我们还传递 runner() 函数,新线程将在其中开始执行。最后,我们传递命令行上提供的整数参数,argv[1]。此时,程序有两个线程:main() 中的初始(或父)线程和在 runner() 函数中执行求和操作的求和(或子)线程。此程序遵循 fork-join 策略:在创建求和线程后,父线程将通过调用 pthread_join() 函数等待它终止。当它调用函数 pthread_exit() 时,求和线程将终止。一旦求和线程返回,父线程将输出共享数据 sum 的值。
使用 Pthreads API 的多线程 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
");
return -1;
}
if (atoi(argv[1]) < 0){
fprintf(stderr,"%d must be >= 0
",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
",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);
}
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP