Hi,
I wrote the following program to understand mutexes. If I run the program , number of threads is shown as zero, even after creating one thread. When running with gdb, it works fine.
The function process is used to update global variable (used to keep track of threads). It looks like the second instance of display (which displays number of threads ) is running before the counter gets incremented. If I add a pthread_join in main thread it works (main thread waits for created thread to complete). Is there a better way to address this and is my understanding correct? Thanks
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
int num_thread=0;
pthread_mutex_t threadcount=PTHREAD_MUTEX_INITIALIZER;
void *process( )
{
pthread_mutex_lock(&threadcount);
num_thread++;
pthread_mutex_unlock(&threadcount);
}
void display()
{
pthread_mutex_lock(&threadcount);
printf("num of threads %d \n",num_thread);
pthread_mutex_unlock(&threadcount);
}
int main()
{
pthread_t tid1, tid2;
int t;
display();
pthread_create(&tid1,NULL,process,&t);
display();
return 0;
}