卓越飞翔博客卓越飞翔博客

卓越飞翔 - 您值得收藏的技术分享站
技术文章16333本站已运行3317

POSIX线程库

POSIX线程库

Pthreads指的是POSIX标准(IEEE 1003.1c),定义了用于线程创建和同步的API。这定义了线程行为的规范,而不是实现。规范可以由操作系统设计者以任何他们希望的方式来实现。因此,许多系统实现了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程序。

卓越飞翔博客
上一篇: 如何使用C++进行跨平台的开发?
下一篇: 如何使用PHP进行图片剪裁和缩放
留言与评论(共有 0 条评论)
   
验证码:
隐藏边栏