欢迎来到天天文库
浏览记录
ID:14270362
大小:161.50 KB
页数:6页
时间:2018-07-27
《使用二个互斥量的多线程程序》由会员上传分享,免费在线阅读,更多相关内容在行业资料-天天文库。
1、#include#include#include#include#include#defineHASH(id)((id)%NHASH)#defineTHREAD_NUM5#defineFOO_NUM10#defineNHASH29structfoo*fh[NHASH];pthread_mutex_thashlock=PTHREAD_MUTEX_INITIALIZER;structfoo{intf_count;pthread_mutex_tf_lock;structfoo*f_next;intf_id;intvisited[THREAD_N
2、UM];intvnum;};structfoo*foo_alloc(intfid){structfoo*fp;inti,idx;if((fp=malloc(sizeof(structfoo)))!=NULL){fp->f_count=1;if(pthread_mutex_init(&fp->f_lock,NULL)!=0){free(fp);returnNULL;}}idx=HASH(fid);pthread_mutex_lock(&hashlock);fp->f_next=fh[idx];fh[idx]=fp;pthread_mutex
3、_lock(&fp->f_lock);pthread_mutex_unlock(&hashlock);for(i=0;i<THREAD_NUM;i++){fp->visited[i]=-1;}pthread_mutex_unlock(&fp->f_lock);returnfp;}voidfoo_hold(inttid,structfoo*fp){pthread_mutex_lock(&fp->f_lock);fp->f_count++;fp->visited[fp->vnum++]=tid;pthread_mutex_unl
4、ock(&fp->f_lock);}structfoo*foo_find(inttid,intfoo_id){structfoo*fp;intidx;idx=HASH(foo_id);pthread_mutex_lock(&hashlock);for(fp=fh[idx];fp!=NULL;fp=fp->f_next){if(fp->f_id==foo_id){foo_hold(tid,fp);break;}}pthread_mutex_unlock(&hashlock);returnfp;}voidfoo_rele(intfid,str
5、uctfoo*fp){structfoo*tfp;intidx;pthread_mutex_lock(&fp->f_lock);if(fp->f_count==1){pthread_mutex_unlock(&fp->f_lock);pthread_mutex_lock(&hashlock);pthread_mutex_lock(&fp->f_lock);if(fp->f_count!=1){fp->f_count--;pthread_mutex_unlock(&fp->f_lock);pthread_mutex_unlock(&hash
6、lock);return;}idx=HASH(fid);tfp=fh[idx];if(tfp==fp){fh[idx]=fp->f_next;}else{while(tfp->f_next!=fp){tfp=tfp->f_next;tfp->f_next=fp->f_next;}}pthread_mutex_unlock(&hashlock);pthread_mutex_unlock(&fp->f_lock);pthread_mutex_destroy(&fp->f_lock);free(fp);}else{fp->f_count--;p
7、thread_mutex_unlock(&fp->f_lock);}}void*thrd_func_0(void*arg){inttid=(int)arg;inti,j,foo_id;i=j=foo_id=0;structfoo*fp=NULL;for(i=0;i<THREAD_NUM;i++)for(j=0;j<FOO_NUM;j++){foo_id=j+i*FOO_NUM;fp=foo_find(tid,foo_id);if(NULL!=fp){foo_rele(foo_id,fp);}usleep(100
8、);}returnNULL;}void*thrd_func_1(void*arg){inttid=(int)arg;inti,j,foo_id;i=j=foo_id=0;structfoo*f
此文档下载收益归作者所有