Linux IPC (Mutex & cond)

Source: Internet
Author: User
Tags mutex semaphore

/*
* This demo shows the use semaphore between threads.
*
*/

#include <pthread.h>
#include <semaphore.h>
#include <sys/types.h>
#include <stdio.h>
#include <unistd.h>

/*
* Global shared Resource
*/
struct Shared_resouce {
int global_count;
pthread_mutex_t Mutex;
pthread_cond_t cond;
} shr_res;


void Mutex_clean (void *mutex)
{
Pthread_mutex_unlock ((pthread_mutex_t*) mutex);
}

void* thread_fun (void *arg)
{
printf ("Thread:%ld active.\n", pthread_self ());

while (1)
{
Pthread_mutex_lock (&shr_res.mutex);
while (shr_res.global_count <= 0)
{
Pthread_cond_wait (&shr_res.cond, &shr_res.mutex);
}

shr_res.global_count--;
printf ("Thread%d decrease Globar var.\n", pthread_self ());

Pthread_mutex_unlock (&shr_res.mutex);

Sleep (2);
}
}
int main (int argc, char **argv)
{
pthread_t Id1, Id2;

/*
* Initialize globar var
*/
Shr_res.global_count = 0;
if (Pthread_mutex_init (&shr_res.mutex, NULL)! = 0)
{
printf ("Initialize mutex error!");
Exit (-1);
}

if (Pthread_cond_init (&shr_res.cond, NULL)! = 0)
{
printf ("Initialize condation var error!");
Exit (-1);
}

Pthread_create (&AMP;ID1, NULL, thread_fun, NULL);
Pthread_create (&id2, NULL, thread_fun, NULL);

/*
* In main thread, loop of increasing shr_res.global_count.
*/
while (1)
{
Pthread_mutex_lock (&shr_res.mutex);

printf ("Main Thread increase global var.\n");
shr_res.global_count++;
if (Shr_res.global_count > 0)
{
Pthread_cond_signal (&shr_res.cond);
}

Pthread_mutex_unlock (&shr_res.mutex);

Sleep (3);
}

Pthread_join (ID1, NULL);
Pthread_join (Id2, NULL);

Pthread_cond_destroy (&shr_res.cond);
Pthread_mutex_destroy (&shr_res.mutex);

Exit (0);
}




Linux IPC (Mutex & cond)

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.