总结
豆包 AI 助手文章总结
首页 > 后端开发 > C++ > 正文

POSIX线程库

王林
发布: 2023-08-25 16:29:06
转载
923人浏览过

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 </p><p>");
      return -1;
   }
   if (atoi(argv[1]) < 0){
      fprintf(stderr,"%d must be >= 0</p><p>",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</p><p>",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程序。

以上就是POSIX线程库的详细内容,更多请关注php中文网其它相关文章!

最佳 Windows 性能的顶级免费优化软件
最佳 Windows 性能的顶级免费优化软件

每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。

下载
相关标签:
来源:tutorialspoint网
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新问题
豆包 AI 助手文章总结
开源免费商场系统广告
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号