- 1、本文档共5页,可阅读全部内容。
- 2、有哪些信誉好的足球投注网站(book118)网站文档一经付费(服务费),不意味着购买了该文档的版权,仅供个人/单位学习、研究之用,不得用于商业用途,未经授权,严禁复制、发行、汇编、翻译或者网络传播等,侵权必究。
- 3、本站所有内容均由合作方或网友上传,本站不对文档的完整性、权威性及其观点立场正确性做任何保证或承诺!文档内容仅供研究参考,付费前请自行鉴别。如您付费,意味着您自己接受本站规则且自行承担风险,本站不退款、不进行额外附加服务;查看《如何避免下载的几个坑》。如果您已付费下载过本站文档,您可以点击 这里二次下载。
- 4、如文档侵犯商业秘密、侵犯著作权、侵犯人身权等,请点击“版权申诉”(推荐),也可以打举报电话:400-050-0827(电话支持时间:9:00-18:30)。
查看更多
Linux下多线程编程-Pthread与Semaphore的使用
2008-11-20 21:52
摘自: 作者: 姚继锋 (2001-08-11 09:05:00)关键字:Linux 多线程 Pthread semaphore简单的多线程编程Linux系统下的多线程遵循POSIX线程接口,称为pthread。编写Linux下的多线程程序,需要使用头文件pthread.h,连接时需要使用库libpthread.a。顺便说一下,Linux下pthread的实现是通过系统调用clone()来实现的。clone()是Linux所特有的系统调用,它的使用方式类似fork,关于clone()的详细情况,有兴趣的读者可以去查看有关文档说明。下面我们展示一个最简单的多线程程序 example1.c。/* example.c*/#include stdio.h#include pthread.hvoid thread(void){??? int i;??? ??? for( i = 0;i 3; i++ )??? ??? printf(This is a pthread.\n);}int main(void){??? pthread_t id;??? int i,ret;??? ??? ret = pthread_create( id, NULL, (void *)thread, NULL );??? if ( ret!=0 ) {??? ??? printf (Create pthread error!\n);??? ??? exit (1);??? }??? ??? for( i = 0; i 3; i++ )??? ??? printf(This is the main process.\n);??? ??? ??? pthread_join(id,NULL);??? ??? return (0);}我们编译此程序:gcc example1.c -lpthread -o example1运行example1,我们得到如下结果:This is the main process.This is a pthread.This is the main process.This is the main process.This is a pthread.This is a pthread.再次运行,我们可能得到如下结果:This is a pthread.This is the main process.This is a pthread.This is the main process.This is a pthread.This is the main process.前后两次结果不一样,这是两个线程争夺CPU资源的结果。上面的示例中,我们使用到了两个函数, ??? pthread_create和pthread_join,并声明了一个pthread_t型的变量。pthread_t在头文件/usr/include/bits/pthreadtypes.h中定义:typedef unsigned long int pthread_t;它是一个线程的标识符。函数pthread_create用来创建一个线程,它的原型为:extern int pthread_create __P ((pthread_t *__thread, __const pthread_attr_t *__attr,void *(*__start_routine) (void *), void *__arg));第一个参数为指向线程标识符的指针,第二个参数用来设置线程属性,第三个参数是线程运行函数的起始地址,最后一个参数是运行函数的参数。这里,我们的函数thread不需要参数,所以最后一个参数设为空指针。第二个参数我们也设为空指针,这样将生成默认属性的线程。对线程属性的设定和修改我们将在下一节阐述。当创建线程成功时,函数返回0,若不为0则说明创建线程失败,常见的错误返回代码为EAGAIN和EINVAL。前者表示系统限制创建新的线程,例如线程数目过多了;后者表示第二个参数代表的线程属性值非法。创建线程成功后,新创建的线程则运行参数三和参数四确定的函数,原来的线程则继续运行下一行代码。函数pthread_join用来等待一个线程的结束。函数原型为:extern int pthread_join __P ((pthread_t __th, void **__thread_return));第一个参数为被等待的线程标识符,第二个参数为一个用户定义的指针,它可以
您可能关注的文档
- 南大 数据库原理第二次作业指南.doc
- 第八章 公司概论作业题2、3、5次作业.doc
- 第七章 模式识别习题答案.doc
- 《施工组织和计划》复习试题答案.doc
- 系统平台实验7-线程同步和多线程编程.doc
- 第3课 再践javascript对象、原型、属性、构造函数、扩展、json.doc
- 管道试压和冲洗方案.doc
- 第八章 客户端装维上门服务要求.doc
- 数据库原理与应用教学目的、内容、重点、难点.doc
- 项目质量计划实施细则要领.doc
- 成都青年磁场项目策划方案手册.pptx
- 新京报:2024年中国青年消费趋势报告.pptx
- 沃尔玛全球电商店铺运营90天指南.pptx
- 哔哩哔哩·美食纪录片招商方案.pptx
- 2023年度国家一级博物馆传播力研究报告.pdf
- -高中语文 第五单元素质升级检测 新人教版选修《中国小说欣赏》.doc
- 高中数学 1-1-2 圆柱、圆锥、圆台、球的结构特征、简单组合体的结构特征能力强化提升 新人教A版必修2.doc
- 高中数学 4-2-2 圆与圆的位置关系能力强化提升 新人教A版必修2.doc
- 高中数学 2-1-2 空间中直线与直线之间的位置关系能力强化提升 新人教A版必修2.doc
- 高中物理 1.2 库仑定律练习 新人教版选修3-1.doc
文档评论(0)