Hi All
I want to write a multithreaded program where I want to print string using 2 threads. ie. if String is:
Code:
char a[] = {"Welcome to the world of Multithreading Programming"};
Thread 1: Welcome
Thread 2: To
Thread 1:The
Thread 2: World
and so on.
I used condition variable to preform this but not working fine.
Code:
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
pthread_mutex_t count_mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t condition_var = PTHREAD_COND_INITIALIZER;
void *functionCount1();
void *functionCount2();
int count = 0;
main()
{
char a[] = {"Welcome to the world of Multithreading Programming"};
int i = 0,rc ;
pthread_t thread1, thread2;
rc = pthread_create( &thread1, NULL, &functionCount1, a);
pthread_create( &thread2, NULL, &functionCount2, a);
pthread_join( thread1, NULL);
pthread_join( thread2, NULL);
exit(0);
}
void *functionCount1(char *a)
{
for(;;)
{
pthread_mutex_lock( &count_mutex );
pthread_cond_wait( &condition_var, &count_mutex );
while (a[count] != ' ' && a[count] != '\0')
{
printf("%c",a[count]);
count++;
}
pthread_mutex_unlock( &count_mutex );
if(a[count] == '\0') return(NULL);
}
}
void *functionCount2(char *a)
{
for(;;)
{
pthread_mutex_lock( &count_mutex );
while (a[count] != ' ' && a[count] != '\0')
{
printf("%c",a[count]);
count++;
}
pthread_cond_signal( &condition_var );
pthread_mutex_unlock( &count_mutex );
if(a[count] == '\0') return(NULL);
}
}
When I run this code, nothing is happening.
The same thing I have used for printing numbers in alternate seq. and it works fine.
Can any suggest problem with the above code.
Thanks