I'm learning how to use thread in C, I have created a program which invokes two threads and prints something at the same time.
Here is my 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;
#define COUNT_DONE 10
int main()
{
pthread_t thread1, thread2;
pthread_create( &thread1, NULL, &functionCount1, &count);
pthread_create( &thread2, NULL, &functionCount2, &count);
pthread_join( thread1, NULL);
pthread_join( thread2, NULL);
printf("Final count: %d\n", count);
exit(0);
}
//Print count when count is even
void *functionCount1()
{
for(;;)
{
pthread_mutex_lock( &count_mutex );
pthread_cond_wait( &condition_var, &count_mutex );
count++;
printf("Counter value functionEven: %d\n",count);
pthread_mutex_unlock( &count_mutex );
}
}
//Print count when count is odd
void *functionCount2(void *arg)
{
for(;;)
{
pthread_mutex_lock( &count_mutex );
if(count%2 == 0)
{
pthread_cond_signal( &condition_var );
}
if(count % 2 != 0)
{
count++;
printf("Counter value functionOdd: %d\n",count);
}
pthread_mutex_unlock( &count_mutex );
if(count >= COUNT_DONE) return(NULL);
}
}
The output is correct, but the thread seems like still running on the background. How can I fix that issue and terminating the thread correctly?