Sunday, March 21, 2021

multithread synchronization using semaphore

 


#include <iostream>

#include<pthread.h>

#include<semaphore.h>


using namespace std;


pthread_t t[5];

sem_t sem[5];


int c = 0;

#define NUM 30


void* inc(void* p)

{

    while(c < NUM)

    {

        if(sem_wait(&sem[0]) == 0)

        {

            cout<<"T0 inc:"<<++c<<endl;

            sem_post(&sem[1]);

        }

    }

    

    pthread_exit(NULL);

}


void* odd(void* p)

{

    while(c < NUM)

    {

        if (sem_wait(&sem[1]) == 0)

        {

            if (0 != c % 2)

            {

                cout<<c<<":T1 odd"<<endl;

            }

            sem_post(&sem[2]);

        }

    }

    

    pthread_exit(NULL);

}


void* even(void* p)

{

    while(c < NUM)

    {

        if (sem_wait(&sem[2]) == 0)

        {

            if (0 == c % 2)

            {

                cout<<c<<":T2 even"<<endl;

            }

            sem_post(&sem[3]);

        }

    }

    

    pthread_exit(NULL);

}


void* mul2(void* p)

{

    while(c < NUM)

    {

        if (sem_wait(&sem[3]) == 0)

        {

            if (0 == c % 2)

            {

                cout<<c<<": T3 mul by 2"<<endl;

            }

            sem_post(&sem[4]);

        }

    }

    

    pthread_exit(NULL);

}


void* mul5(void* p)

{

    while(c < NUM)

    {

        if (sem_wait(&sem[4]) == 0)

        {

            if (0 == c % 5)

            {

                cout<<c<<": T4 mul by 5"<<endl;

            }

            sem_post(&sem[0]);

        }

    }

    

    pthread_exit(NULL);

}


int main()

{

    sem_init(&sem[0], 0, 1);

    sem_init(&sem[1], 0, 0);

    sem_init(&sem[2], 0, 0);

    sem_init(&sem[3], 0, 0);

    sem_init(&sem[4], 0, 0);


    pthread_create(&t[0], NULL, &inc, NULL);

    pthread_create(&t[1], NULL, &odd, NULL);

    pthread_create(&t[2], NULL, &even, NULL);

    pthread_create(&t[3], NULL, &mul2, NULL);

    pthread_create(&t[4], NULL, &mul5, NULL);


    pthread_join(t[0], NULL);

    pthread_join(t[1], NULL);

    pthread_join(t[2], NULL);

    pthread_join(t[3], NULL);

    pthread_join(t[4], NULL);

    

    pthread_exit(NULL);

    return 0;

}

No comments:

Post a Comment