Hi ,
Below is the code for printing even/odd numbers alternatively.But some how i am not able to achieve the result.
I have seen a version with while loop http://www.bogotobogo.com/cplusplus/quiz_multithreading.php working perfect.
But i would like to use one thread for printing one value instead of same thread running in loop as shown in example.
I hope my main function is correct, just by modifying my thread functions can i achieve my desired out put.
please help.
#include <stdio.h>
#include <pthread.h>
void* OddFunc(void *p);
void* EvenFunc(void *p);
int g_var = 0;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond_v = PTHREAD_COND_INITIALIZER;
#define NOOFTHRDS 10
int main()
{
pthread_t o_tid[NOOFTHRDS],e_tid[NOOFTHRDS];
pthread_attr_t attr;
int i ;
void *status;
pthread_attr_init(&attr);
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
for( i= 0;i<NOOFTHRDS;i++) {
pthread_create(&o_tid[i],NULL,OddFunc,&i);
pthread_create(&e_tid[i],NULL,EvenFunc,&i);
}
for( i= 0;i<NOOFTHRDS;i++) {
pthread_join(e_tid[i],&status);
pthread_join(o_tid[i],&status);
}
pthread_mutex_destroy(&mutex);
pthread_cond_destroy(&cond_v);
// pthread_exit(NULL);
return 0;
}
void* OddFunc(void *p)
{
if(g_var%2 != 1) {
pthread_mutex_lock(&mutex);
pthread_cond_wait(&cond_v, &mutex);
printf("I= %d , O: %d\n",*(int *)p, g_var++);
}
else{
pthread_mutex_lock(&mutex);
printf("I= %d , O: %d\n",*(int *)p, g_var++);
pthread_mutex_unlock(&mutex);
pthread_cond_signal(&cond_v);
}
pthread_exit(NULL);
}
void* EvenFunc(void *p)
{
if(g_var%2 != 0){
pthread_mutex_lock(&mutex);
pthread_cond_wait(&cond_v, &mutex);
printf("I= %d , E: %d\n", *(int *)p,g_var++);
}
else {
pthread_mutex_lock(&mutex);
printf("I= %d , E: %d\n", *(int *)p,g_var++);
pthread_mutex_unlock(&mutex);
pthread_cond_signal(&cond_v);
}
pthread_exit(NULL);
}