pthread question : global variable not updated

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;
 
  }

Threads are independent, remember. You can't make any assumptions about timing unless you enforce them yourself.

Your mutex looks correct, and will stop them from accessing it simultaneously. Nothing stops main() from rolling along and printing the global value before your thread changes it, though!

In fact, it's quite likely. Threads often don't start instantly, it might wait until the next context switch to launch them, and the next context switch could easily be the exit() system call.

You can visualize what Corona688 said by "forcing" a context switch: if you put the main thread to sleep "for enough time" just after the new thread creation:

int main()
{
   pthread_t tid1, tid2;
    int t;
 
    display();
    pthread_create(&tid1,NULL,process,&t);
    sleep(1); /* give some time so the new created thread will have a chance to run before main thread calls display function */
    display();
   return 0;
 
  }