/*
** Concurrent Load and Store
** Use "cc -S ex_pload_store.c" to get ex_pload_store.s
** Copyright Rolf Riesen 2008
**
*/
#include <stdio.h>
#include <stdlib.h>     /* For strtol(), exit(), malloc() */
#include <pthread.h>	/* For pthread_*() */


/* Globals */
int value;
#define DEFAULT_NUM_THREADS     (4)


/* Local functions */
static void *work_func(void *arg);



int
main(int argc, char *argv[])
{

int nproc;
int i, rc;
int *ranks;
pthread_t *thread;


 
    /* Initialize some variables */
    nproc= DEFAULT_NUM_THREADS;		/* Default number of threads */
    value= 0;


    /* Allocate storage for the thread handles */
    thread= (pthread_t *)malloc(nproc * sizeof(pthread_t));
    if (thread == NULL)   {
	fprintf(stderr, "Out of memory!\n");
	exit(-1);
    }


    /* Allocate storage for the thread arguments */
    ranks= (int *)malloc(nproc * sizeof(int));
    if (ranks == NULL)   {
	fprintf(stderr, "Out of memory!\n");
	exit(-1);
    }

    for (i= 0; i < nproc; i++)   {
	ranks[i]= i;
	rc= pthread_create(&thread[i], NULL, work_func, (void *)&ranks[i]);
	if (rc != 0)   {
	    perror("pthread_create() failed");
	    exit(-1); 
	}
    }

    for (i= 0; i < nproc; i++)   {
	pthread_join(thread[i], NULL);
    }

    printf("value is now %d\n", value);

    return 0; 

}  /* end of main() */



static void *
work_func(void *arg)
{

int my_rank;


    my_rank= *(int *)arg;

    if ((my_rank % 2) == 1)   {
        /* If I'm an odd rank */
        value= value + 12;
    } else   {
        /* If I'm an even rank */
        value= value - 3;
    }

    return NULL;

}  /* end of hello_func() */
