#include<stdlib.h>
#include <pthread.h>
#include "tlpi_hdr.h"
#include <stdio.h>
static volatile int glob = 0;
static struct {
pthread_t t1,t2;
} *thread;
static void * /* Loop 'arg' times incrementing 'glob' */
threadFunc(void *arg)
{
int loops = *((int *) arg);
int loc, j, s;
if (s != 0)
errExitEN(s, "pthread_mutex_lock");
for (j = 0; j < loops; j++) {
loc = glob;
printf("The ID of this thread is: %u\n", (unsigned int)pthread_self());
printf("glob = %d\n", glob);
sleep(2);
loc++;
glob = loc;
if (s != 0)
errExitEN(s, "pthread_mutex_unlock");
}
return NULL;
}
int
main(int argc, char *argv[])
{
int loops=0;
int s;
loops = (argc > 1) ? getInt(argv[1], GN_GT_0, "num-loops") : 10000000;
s = pthread_create(&thread[loops].t1, NULL, threadFunc, &loops);
if (s != 0)
errExitEN(s, "pthread_create");
s = pthread_create(&thread[loops].t2, NULL, threadFunc, &loops);
if (s != 0)
errExitEN(s, "pthread_create");
s = pthread_join(thread[loops].t1, NULL);
if (s != 0)
errExitEN(s, "pthread_join");
s = pthread_join(thread[loops].t2, NULL);
if (s != 0)
errExitEN(s, "pthread_join");
printf("final glob = %d\n", glob);
exit(EXIT_SUCCESS);
}
You don't allocate any memory for your "thread" variable to point to.
So "thread[loops]" point to some random location.
1 Like