/*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);//Because the shared segment is too fast to achieve synchronization
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]#
*/
A well-known semaphore synchronization between multiple threads