码迷,mamicode.com
首页 > 编程语言 > 详细

有名信号量在多线程间的同步

时间:2014-11-13 23:59:34      阅读:425      评论:0      收藏:0      [点我收藏+]

标签:des   style   blog   io   color   ar   os   sp   for   

/*semopen_pth.c*/
#include <stdio.h>
#include <semaphore.h>
#include <fcntl.h>
#include <pthread.h>
#include<stdlib.h>
void print();
void * thread_function(void *arg);
sem_t * sem;
int main(int argc,char * argv[])
{
int n=0,i=0;
pthread_t tid[5];
if(argc != 2)
{
printf("Usage:%s name.\n",argv[0]);
exit(0);
}
//init semaphore
sem=sem_open(argv[1],O_CREAT,0644,3);
while(n++<5)
{
if((pthread_create(&tid[i],NULL,thread_function,NULL))!=0)
{
printf("can‘t create pthread.\n");
exit(0);
}
i++;
}
for(i=0;i<5;i++)
pthread_join(tid[i],NULL);

sem_close(sem);
sem_unlink(argv[1]);
return 0;
}

void * thread_function(void *arg)
{
sem_wait(sem);
print();
sleep(1); //因为共享段执行过快,不能达到同步效果,所以需要睡眠
sem_post(sem);

printf("finish, pthread_id is%lu\n",pthread_self());
}

void print()
{
int value;
printf("pthread_id is %lu, get the resource\n",pthread_self());
sem_getvalue(sem,&value);
printf("now,the semaphore value is %d\n",value);
}
/*
[root@linux Desktop]# gcc b.c -lpthread -lrt
[root@linux Desktop]# ./a.out yy
pthread_id is 3046529904, get the resource
now,the semaphore value is 2
pthread_id is 3036040048, get the resource
now,the semaphore value is 1
pthread_id is 3057019760, get the resource
now,the semaphore value is 0
finish, pthread_id is3046529904
finish, pthread_id is3036040048
finish, pthread_id is3057019760
pthread_id is 3067509616, get the resource
now,the semaphore value is 2
pthread_id is 3077999472, get the resource
now,the semaphore value is 1
finish, pthread_id is3067509616
finish, pthread_id is3077999472
[root@linux Desktop]#

*/

有名信号量在多线程间的同步

标签:des   style   blog   io   color   ar   os   sp   for   

原文地址:http://www.cnblogs.com/leijiangtao/p/4096059.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!