DigestCPP

Lets Understand With Example

  • Home
  • Design Principal
  • Design Patterns
  • C++ 11 Features
  • C++11 Multithreading
  • Contact Us

thread synchronization in c

Create 2 thread and print ping and pong multiple time.

There are 2 ways/method to synchronise threads:

  • mutex with conditional variable
  • semaphore

Source code of multi threading c with semaphore:

#include <stdio.h>
#include<pthread.h>
#include <semaphore.h>
#include <unistd.h>
//using namespace std;

int i = 0;
sem_t sR;
sem_t sW;


void* Writer(void*)
{
    printf("In Writer\n");
    while(i!= 10)
    {
        ++i;
        printf("Writer: %d\n",i);
        sem_post(&sW);
        sem_wait(&sR);
    }

}

void* Reader(void*)
{
    printf("In Reader\n");
    while(i!= 10)
    {
        sem_wait(&sW);
        printf("Reader: %d\n",i);
        sem_post(&sR);
    }

}


int main()
{
    pthread_t t1, t2;
    printf("In Main\n");
    sem_init(&sR, 0, 0);
    sem_init(&sW, 0, 0);
    pthread_create(&t1, 0, Writer, 0);
    pthread_create(&t2, 0, Reader, 0);
    pthread_join(t1, 0);
    pthread_join(t2, 0);
    sem_destroy(&sW);
    sem_destroy(&sR);
    return 0;
}

Source code of multi threading c with mutex:

#include <stdio.h>
#include<pthread.h>
#include <semaphore.h>
#include <unistd.h>

int i = 0;

pthread_mutex_t m1;
pthread_cond_t condR;
pthread_cond_t condW;


void* MyWriter(void*)
{
    printf("In Writer\n");
    sleep(1);
    pthread_mutex_lock(&m1);
    while(i!= 10)
    {
        ++i;
        printf("Writer: %d\n",i);
        pthread_cond_signal( & condR);
        pthread_cond_wait( & condW, & m1 );

    }
    pthread_mutex_unlock(&m1);

}

void* MyReader(void*)
{
    printf("In Reader\n");
    pthread_mutex_lock(&m1);
    while(i!= 10)
    {
        pthread_cond_wait( & condR, & m1 );
        printf("Reader: %d\n",i);
        pthread_cond_signal( & condW);
    }
    pthread_mutex_unlock(&m1);

}

int main()
{
    pthread_t t1, t2;
    printf("In Main\n");
    pthread_mutex_init(&m1, 0);
    pthread_cond_init(&condR, NULL);
    pthread_cond_init(&condW, NULL);
    pthread_create(&t1, 0, MyWriter, 0);
    pthread_create(&t2, 0, MyReader, 0);
    pthread_join(t1, 0);
    pthread_join(t2, 0);
    return 0;
}

Output:

In Main
In Writer
Writer: 1
In Reader
Reader: 1
Writer: 2
Reader: 2
Writer: 3
Reader: 3
Writer: 4
Reader: 4
Writer: 5
Reader: 5
Writer: 6
Reader: 6
Writer: 7
Reader: 7
Writer: 8
Reader: 8
Writer: 9
Reader: 9
Writer: 10
Reader: 10

Primary Sidebar




DigestCPP © 2023. All rights reserved.

    About Privacy Policy Terms and Conditions Contact Us Disclaimer