A well-known semaphore synchronization between multiple threads

Source: Internet
Author: User

/*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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.