Global Variables

It is very important to remember that all threads and the main program run in the same address space allocated to the main program. This implies that names declared as external can be accessed by all threads. However, names declared local to a function are still local to that function.

Example

Let us consider the following program. You can click here to download a copy.

#include  <stdio.h>
#include  <thread.h>

#define   MAX_ITERATION  2000

int       Counter = 0;

void  *Counting(void *DontNeedIt)
{
     int  i;

     for (i = 1; i <= MAX_ITERATION; i++) {
          Counter++;
          printf("Thread Counting() has updated the counter to %d\n", Counter);
     }          
     thr_exit(0);
}

void  *Peeking(void *DontNeedIt)
{
     int  i;
     int  j, k;

     for (i = 1; i <= MAX_ITERATION; i++)
          if (i % 100 == 0)
               printf("     Thread Peeking() saw the counter as %d\n", Counter);
          else           /* the following is a dummy loop */
               for (j = k = 0; j <= MAX_ITERATION/2; j++, k += j)
                    ;
     thr_exit(0);
}

void  main(void)
{
     thread_t  FirstThread, SecondThread;
     size_t    StatusFromA, StatusFromB;

     thr_create(NULL, 0, Counting, (void *) NULL, 0, &FirstThread);
     thr_create(NULL, 0, Peeking, (void *) NULL, 0, &SecondThread);

     thr_join(FirstThread, 0, (void *) &StatusFromA);
     thr_join(SecondThread, 0, (void *) &StatusFromB);
}