Tuesday, December 21, 2010

C Threads : Two synchronized threads to print alternate numbers.

Here, i was trying to print alternate numbers starting from 0 to 11. I have two threads, one will always prints odd numbers and other will print only even number.

My intension is to print odd and even alternately. To ensure the synchronization, i am using MUTEXES.

Sample code :
pthread_mutex_lock (&mutexsum);
gCount++;
std::cout<<gCount<<endl;
pthread_mutex_unlock (&mutexsum);

Full version of the code is as below. Here I use pthread libraries to create the threads.
My reference  : https://computing.llnl.gov/tutorials/pthreads/.

#include <iostream>
#include<stdio.h>
#include <pthread.h>
using namespace std;
pthread_mutex_t mutexsum;
int gCount=0;

void *odd(void* ptr)
{
while(gCount<=10)
{
   if(gCount%2==1) //If even
   {
        pthread_mutex_lock (&mutexsum);
        gCount++;
        std::cout<<gCount<<endl;
        pthread_mutex_unlock (&mutexsum);
   }
}
}

void *even(void* ptr)
{
while(gCount<10)
{
   if(gCount%2==0) //If even
   {
        pthread_mutex_lock (&mutexsum);
        gCount++;
        std::cout<<gCount<<endl;
        pthread_mutex_unlock (&mutexsum);
   }
}
}

int main()
{

    pthread_t T_even, T_odd;
    int T_rt1,T_rt2;
    void *status;
    pthread_mutex_init(&mutexsum, NULL);
    std::cout << "Hello world!" << endl;
    int i=0; // this variable has no significance
    T_rt1= pthread_create(&T_odd,NULL,odd,&i); // here variable i has no significance. it can be null also. I am passing it as a trial
    T_rt2=pthread_create(&T_even,NULL,even,&i);

    pthread_join(T_odd,&status);
    pthread_join(T_even,&status);

    pthread_exit(NULL);
    return 0;
}

Send me your comments.

No comments:

Post a Comment