/*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);
}
/*
[[email protected] Desktop]# gcc b.c -lpthread -lrt
[[email protected] 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
[[email protected] Desktop]#
*/