Hello, I am trying to understand pthreads by example. I have made the following code that is giving different answers everytime I run! Could anyone explain the bug please? TIA, Sviiya
The code is here:
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#define NUM_THREADS 4
struct thread_data {
int thread_id;
int sum;
};
struct thread_data thread_data_array[NUM_THREADS];
void *PrintHello(void *threadarg)
{
struct thread_data *my_data;
int taskid;
int sum;
my_data = (struct thread_data *) threadarg;
taskid = my_data->thread_id;
sum = my_data->sum;
printf("Hello World! It's me, thread #%d\n", taskid);
return my_data;
}
int main ()
{
pthread_t threads[NUM_THREADS];
int rc;
long t;
int sum=0;
for (t=0; t < NUM_THREADS; t++) {
printf("Hi! %ld\n", t);
threads[t] = t;
thread_data_array[t].thread_id = t;
thread_data_array[t].sum = sum;
rc = pthread_create(&threads[t], NULL, PrintHello, (void *) &thread_data_array[t]);
}
return 0;
}
The output is here:
[user@office tmp]$ ./a.out
Hi! 0
Hi! 1
Hello World! It's me, thread #0
Hello World! It's me, thread #1
Hi! 2
Hi! 3
Hello World! It's me, thread #2
[user@office tmp]$ ./a.out
Hi! 0
Hi! 1
Hello World! It's me, thread #0
Hello World! It's me, thread #1
Hi! 2
Hi! 3
Hello World! It's me, thread #2
Hello World! It's me, thread #3
[user@office tmp]$ ./a.out
Hi! 0
Hello World! It's me, thread #0
Hi! 1
Hello World! It's me, thread #1
Hi! 2
Hello World! It's me, thread #2
Hi! 3
Hello World! It's me, thread #3
[user@office tmp]$ ./a.out
Hi! 0
Hi! 1
Hello World! It's me, thread #0
Hi! 2
Hi! 3
Hello World! It's me, thread #3
[user@office tmp]$