- 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.h
void 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));
第一个参数为指向线程标识符的指针, 第二个参
您可能关注的文档
最近下载
- 危险化学品生产经营单位安全管理.pptx VIP
- DBJ33_T 1283-2022顶管工程技术规程.pdf VIP
- 《防止电力建设工程施工安全事故三十项重点要求》宣贯与解读.pdf VIP
- 新能源汽车高压安全操作规范.pptx VIP
- 吉利汽车财务报表分析.docx
- 2024年中考语文试题分项汇编:词语运用(第03期)(解析版).pdf VIP
- SMW工法围护桩监理实施细则[全面]范本.doc VIP
- 浅谈市政工程项目成本控制开源与节流.doc VIP
- 最新人教版数学一年级下册第七单元《7.3 数量关系》教学课件(2025年春-新教材).pptx VIP
- 2024年中考语文一轮专题复习:图文转换 专项练习题(Word版,含答案).docx VIP
文档评论(0)