linux下C语言多线程编程实例.doc
上传人:qw****27 上传时间:2024-09-12 格式:DOC 页数:6 大小:43KB 金币:15 举报 版权申诉
预览加载中,请您耐心等待几秒...

linux下C语言多线程编程实例.doc

linux下C语言多线程编程实例.doc

预览

在线预览结束,喜欢就下载吧,查找使用更方便

15 金币

下载此文档

如果您无法下载资料,请参考说明:

1、部分资料下载需要金币,请确保您的账户上有足够的金币

2、已购买过的文档,再次下载不重复扣费

3、资料包下载后请先用软件解压,在使用对应软件打开

linux下C语言多线程编程实例2007年11月29日星期四10:39学东西,往往实例才是最让人感兴趣的,老是学基础理论,不动手,感觉没有成就感,呵呵。下面先来一个实例。我们通过创建两个线程来实现对一个数的递加。或许这个实例没有实际运用的价值,但是稍微改动一下,我们就可以用到其他地方去拉。下面是我们的代码:/*thread_example.c:cmultiplethreadprogramminginlinux*author:falcon*E-mail:tunzhj03@st.lzu.edu.cn*/#include<pthread.h>#include<stdio.h>#include<sys/time.h>#include<string.h>#defineMAX10pthread_tthread[2];pthread_mutex_tmut;intnumber=0,i;void*thread1(){printf("thread1:I'mthread1\n");for(i=0;i<MAX;i++){printf("thread1:number=%d\n",number);pthread_mutex_lock(&mut);number++;pthread_mutex_unlock(&mut);sleep(2);}printf("thread1:主函数在等我完成任务吗?\n");pthread_exit(NULL);}void*thread2(){printf("thread2:I'mthread2\n");for(i=0;i<MAX;i++){printf("thread2:number=%d\n",number);pthread_mutex_lock(&mut);number++;pthread_mutex_unlock(&mut);sleep(3);}printf("thread2:主函数在等我完成任务吗?\n");pthread_exit(NULL);}voidthread_create(void){inttemp;memset(&thread,0,sizeof(thread));//comment1/*创建线程*/if((temp=pthread_create(&thread[0],NULL,thread1,NULL))!=0)//comment2printf("线程1创建失败!\n");elseprintf("线程1被创建\n");if((temp=pthread_create(&thread[1],NULL,thread2,NULL))!=0)//comment3printf("线程2创建失败");elseprintf("线程2被创建\n");}voidthread_wait(void){/*等待线程结束*/if(thread[0]!=0){//comment4pthread_join(thread[0],NULL);printf("线程1已经结束\n");}if(thread[1]!=0){//comment5pthread_join(thread[1],NULL);printf("线程2已经结束\n");}}intmain(){/*用默认属性初始化互斥锁*/pthread_mutex_init(&mut,NULL);printf("我是主函数哦,我正在创建线程,呵呵\n");thread_create();printf("我是主函数哦,我正在等待线程完成任务阿,呵呵\n");thread_wait();return0;}下面我们先来编译、执行一下引文:falcon@falcon:~/program/c/code/ftp$gcc-lpthread-othread_examplethread_example.cfalcon@falcon:~/program/c/code/ftp$./thread_example我是主函数哦,我正在创建线程,呵呵线程1被创建线程2被创建我是主函数哦,我正在等待线程完成任务阿,呵呵thread1:I'mthread1thread1:number=0thread2:I'mthread2thread2:number=1thread1:number=2thread2:number=3thread1:number=4thread2:number=5thread1:number=6thread1:number=7thread2:number=8thread1:number=9thread2:number=10thr