Pthread example code in C++ with and without synchronization

//Thread example in C++. One thread should prints odd numbers and the other thread should print the even numbers. Example without synchronization.
#include<iostream>
using namespace std;
int count=0; //global variable accessed by two threads
int maxx=10;
void* even(void *v)
{
cout<<"even thread"<<endl;
while(count<maxx)
{
if((count%2)==0)
{
cout<<count++<<" ";
//count++;
}
}
pthread_exit(0);//pthread_exit is called from the thread itself to terminate its execution (and return a result) early.
}
void* odd(void *o)
{
cout<<"odd thread"<<endl;
while(count<maxx)
{
if((count%2)==1)
{
cout<<count++<<" ";
//count++;// then proper order :)
}
}
pthread_exit(0);
}

int main()
{
pthread_t t1;
pthread_t t2;

pthread_create(&t1,NULL,&even,NULL);
pthread_create(&t2,NULL,&odd,NULL);
pthread_join(t1,0);
pthread_join(t2,0);
//pthread_join is called from another thread to wait for a thread to terminate and obtain its return value
cout<<endl;
return 0;
}
//OUTPUT
~$ g++ test1.cpp -lpthread
~$ ./a.out
even thread
0 odd thread
1 3 2 5 4 76  89 
//Improved Example synchronized using mutex and conditional variable.
#include<iostream>
using namespace std;
int count=0;
int maxx=10;
pthread_mutex_t mutex;
pthread_cond_t cond;
void* even(void *v)
{
    //cout<<"even thread"<<endl;
    while(count<maxx)
    {
        pthread_mutex_lock(&mutex);//lock before checking
        while((count%2)==0)
        {
            pthread_cond_wait(&cond,&mutex);//wait until count becomes odd
            //it releases the mutex and it waits till condition cond is signaled as complete and mutex is available.
        }
        cout<<"even "<<count++<<endl;
        pthread_mutex_unlock(&mutex);//release
        pthread_cond_signal(&cond);//signal to another thread
    }
    pthread_exit(0);//pthread_exit is called from the thread itself to terminate its execution (and return a result) early.
}
void* odd(void *o)
{
    while(count<maxx)
    {

        pthread_mutex_lock(&mutex);//lock before checking
        while((count%2)==1)
        {
            pthread_cond_wait(&cond,&mutex);//wait until count becomes odd
        }
        cout<<"odd "<<count++<<endl;
        pthread_mutex_unlock(&mutex);//release
        pthread_cond_signal(&cond);//signal to another thread
    }
    pthread_exit(0);
}
int main()
{
    pthread_t t1;
    pthread_t t2;

    pthread_mutex_init(&mutex, 0);
    pthread_cond_init(&cond, 0);

    pthread_create(&t1,NULL,&even,NULL);
    pthread_create(&t2,NULL,&odd,NULL);
    pthread_join(t1,0);
    pthread_join(t2,0);

    pthread_mutex_destroy(&mutex);
    pthread_cond_destroy(&cond);

    //pthread_join is called from another thread to wait for a thread to terminate and obtain its return value
    cout<<endl;
    return 0;
}
/*
odd 0
even1
odd 2
even3
odd 4
even5
odd 6
even7
odd 9
even10
*/

No comments:

Post a Comment