POSIX线程库
Pthreads是指POSIX标准(IEEE1003.1c),该标准定义了用于线程创建和同步的API。这定义了线程行为的规范,而不是实现。该规范可由OS设计人员以他们希望的任何方式实施。因此,许多系统都实现了Pthreads规范。大多数是UNIX类型的系统,包括Linux,MacOSX和Solaris。尽管Windows本机不支持Pthreads,但某些适用于Windows的第三方实现是可用的。图4.9中所示的C程序演示了基本的PthreadsAPI,该API用于构造多线程程序,该程序在单独的线程中计算非负整数的总和。单独的线程开始在Pthreads程序的指定函数中执行。在下面的程序中,这是runner()方法。该程序开始时,一个控制线程开始于main()。然后在初始化后main(),创建第二个线程以开始控制该runner()函数。两个线程共享全局数据总和。
示例
#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 \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 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);
}使用PthreadsAPI的多线程C程序。
热门推荐
1 训练狗狗工作
4 狗狗定点排便训练
5 狗狗训练吠叫
6 狗狗尿垫训练
7 狗狗训练座
8 狗狗训练攻略
9 狗狗训练记
10 做训练狗狗
11 狗狗训练词
12 狗狗谢谢怎么训练
13 狗狗训练如厕
14 狗狗太凶怎么训练
15 狗狗训练它
16 狗狗克制训练
17 训练基地狗狗
18 怎么样训练狗狗大小硬