Multithreading - Inconsistent Output...

The program below keeps outputting inconsistently both in the order of output and the resulting values. I am using the join functions and mutexes, but doesn't seem to work. Can't someone please explain to me why this may be the case?

#include <iostream>
#include <stdlib.h>
#include <pthread.h>

#define NUM_THREADS 5

/* Create thread argument struct for thr_func() */

typedef struct thread_data_t
int tid;
double stuff;
} thread_data_t;

/* Shared data between threads */
double shared_x;
pthread_mutex_t lock_x;

void *thr_func(void *arg)
thread_data_t *data = (thread_data_t*)arg;
printf("hello from thr_func, thread id: %d\n", data->tid);

/* Get mutex before modifying and printing shared_x */
shared_x += data->stuff;
printf("x = %f\n", shared_x);


int main(int argc, const char ** argv)
pthread_t thr[NUM_THREADS];
int i, rc;

/* Create a thread_data_t argument array */
thread_data_t thr_data[NUM_THREADS];

/*Initializing shared data */
shared_x = 0;

/*Create threads */
for (i = 0; i < NUM_THREADS; ++i)
thr_data[i].tid = i;
thr_data[i].stuff = (i + 1)*NUM_THREADS;
if((rc = pthread_create(&thr[i], NULL, thr_func, &thr_data[i])))
fprintf(stderr, "error: pthread_create, rc: %d\n", rc);

/*Block until all threads complete */
for (i = 0; i < NUM_THREADS; ++i)
pthread_join(thr[i], NULL);

The five threads will increment the x in any order, that's the whole point of running multiple threads at the same time.

Here for example one of my runs:
$ ./test
hello from thr_func, thread id: 0
hello from thr_func, thread id: 1
hello from thr_func, thread id: 4
hello from thr_func, thread id: 2
x = 5.000000
hello from thr_func, thread id: 3
x = 25.000000
x = 35.000000
x = 60.000000
x = 75.000000

as you can see, threads reached the first printf() in order 0,1,4,2,3 and then they grabbed the mutex in order 0,3,1,4,2. On other runs, the ordering was different, as expected.
Topic archived. No new replies allowed.