第一范文网 - 专业文章范例文档资料分享平台

多线程程序设计 for Linux

来源:用户分享 时间:2025/5/28 17:46:22 本文由loading 分享 下载这篇文档手机版
说明:文章内容仅供预览,部分内容可能不全,需要完整文档或者需要复制内容,请下载word后使用。下载word有问题请添加微信号:xxxxxxx或QQ:xxxxxx 处理(尽可能给您提供完整文档),感谢您的支持与谅解。

while(n++<5) /*循环创建5个子线程,使它们同步运行*/ {

if((pthread_create(&a_thread,NULL,thread_function,NULL))!=0) {

perror(“Thread creationfailed”); exit(1); } }

pthread_join(a_thread,NULL); sem_close(bin_sem); sem_unlink(argv[1]);

}

void *thread_function(void *arg) {

sem_wait(sem); /*申请信号灯*/ print(); /*调用共享代码段*/ sleep(1);

sem_post(sem); /*释放信号灯*/

printf(“I’mfinished,my tid is %d\\n”,pthread_self());

}

void print() {

printf(“I getit,mytid is %d\\n”,pthread_self()); sem_getvalue(sem,&val);

printf(“Now the valuehave %d\\n”,val); }

程序用循环的方法建立5个线程,然后让它们调用同一个线程处理函数 thread_function,在函数里我们利用信号量来限制访问共享资源的线程数。共享 资源我们用print函数来代表,在真正编程中它有可以是一个终端设备(如打印 机)或是一段有实际意义的代码。

运行结果为:

#gcc –lpthread –o 8_1 8_1.c #./8_1 test

I getit,my tid is 1082330304 Now thevaluehave 2 Igetit,my pidis 1894 Now thevaluehave 1 Igetit,my pidis 1895

Now thevaluehave 0

I’mfinished,my pid is 1893 I’mfinished,my pid is 1894 I’mfinished,my pid is 1895 I getit,my pidis 1896 Now thevaluehave 2 I getit,mypidis 1897 Now thevaluehave 1

I’mfinished,my pid is 1896 I’mfinished,my pid is 1897

四、posix有名信号灯应用于多进程

下面就是应用Posix有名信号灯的一个小程序。用它来限制访问共享代码的进程数目。 #include #include #include #include voidprint(pid_t);

sem_t*sem;/*定义Posix有名信号灯*/

intval;/*定义信号灯当前值*/

intmain(intargc,char*argv[]) {

intn=0; if(argc!=2) {

printf(“pleaseinputafilename!\\n”); exit(1);

while(n++<5)/*循环创建5个子进程,使它们同步运行*/

}

sem=sem_open(argv[1],O_CREAT,0644,2);/*打开一个信号灯,初值设为2*/

{

if(fork()==0) {

sem_wait(sem);/*申请信号灯*/ print(getpid());/*调用共享代码段*/ sleep(1);

sem_post(sem);/*释放信号灯*/

printf(“I’mfinished,mypidis%d\\n”,getpid()); return0;

}

wait();/*等待所有子进程结束*/ sem_close(sem); sem_unlink(argv[1]);

exit(0);

}

voidprint(pid_tpid) {

printf(“Iget it,mypidis%d\\n”,pid); sem_getvalue(sem,&val);

printf(“Nowthevaluehave%d\\n”,val); }

程序编译后运行会得到如下结果:

#./8_28_2.c

Igetit,mytidis1082330304 Now thevaluehave1 Igetit,mytidis1090718784 Now thevaluehave0

Ifinished,mypidis1082330304 Ifinished,mypidis1090718784 Igetit,mytidis1099107264 Now thevaluehave1 Igetit,mytidis1116841120 Now thevaluehave0

Ifinished,mypidis1099107264 Ifinished,mypidis1116841120 Igetit,mytidis1125329600 Now thevaluehave1

Ifinished,mypidis1125329600

五、基于内存的信号灯

前面已经介绍了Posix有名信号灯。这些信号灯由一个name参数标识,它通常指代文件系统中的某个文件。然而Posix也提供基于内存的信号灯,它们由应用程序分配信号灯的内存空间,然后由系统初始化它们的值。

搜索更多关于: 多线程程序设计 for Linux 的文档
多线程程序设计 for Linux.doc 将本文的Word文档下载到电脑,方便复制、编辑、收藏和打印
本文链接:https://www.diyifanwen.net/c5ubv85lfr605ej21u7vo_7.html(转载请注明文章来源)
热门推荐
Copyright © 2012-2023 第一范文网 版权所有 免责声明 | 联系我们
声明 :本网站尊重并保护知识产权,根据《信息网络传播权保护条例》,如果我们转载的作品侵犯了您的权利,请在一个月内通知我们,我们会及时删除。
客服QQ:xxxxxx 邮箱:xxxxxx@qq.com
渝ICP备2023013149号
Top