POSIX 线程库
Pthreads 是指定义一个线程创建和同步 API 的 POSIX 标准(IEEE 1003.1c)。这定义了线程行为的规范,而不是实现。该规范可以由 OS 设计人员以他们希望的任何方式实现。因此,许多系统都实现了 Pthreads 规范;其中大多数是 UNIX 类型系统,包括 Linux、Mac OS X 和 Solaris。尽管 Windows 本机不支持 Pthreads,但有一些适用于 Windows 的第三方实现。图 4.9 中显示的 C 程序演示了用于构建多线程程序的基本 Pthreads API,该程序计算单独线程中的非负整数的总和。在 Pthreads 程序中,单独的线程从指定函数开始执行。在下方的程序中,这是 runner() 函数。当这个程序开始时,一个单线程控制从 main() 开始。然后,main() 创建一个第二个线程,该线程在 runner() 函数中开始控制,在进行一些初始化之后。两个线程共用全局数据 sum。
示例
#include<pthread.h>
#include<stdio.h>
int sum;
/* this sum data is shared by the thread(s) */
/* threads call this function */
void *runner(void *param);
int main(int argc, char *argv[]){
pthread t tid; /* the thread identifier */
/* set of thread attributes */
pthread attr t attr;
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 now begin control 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);
}使用 Pthreads API 的多线程 C 程序。
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP