im new to multi-thread programming in C. I implemented a thread_create.c file for two thread with a race of chars in linux. But if i wanna do it with a #define n for generical multi-thread file there's some error with pointers
There's the code:
#include <stdio.h>
#include <unistd.h>
#include <pthread.h>
#include <stdlib.h>
#define n 5
struct print_args {
int times;
char characters;
};
void * print_sum(void * parameters) {
struct print_args * pp = (struct print_args *) parameters;
for(int i=0; i<= pp->times; i++) {
printf("%c", pp->characters);
fflush(stdout);
sleep(1);
}
return (void *)&(pp->times);
}
int main() {
pthread_t t[n];
srand(time(NULL));
struct print_args t_args[n];
char first = 'A';
int *t_returnValue[n];
for(int j=0; j<n; j++) {
t_args[j].times = rand() % 10;
t_args[j].characters = first;
first++;
}
for(int j=0; j<n; j++) {
pthread_create(&t[j], NULL, &print_sum, &t_args[j]);
}
for(int j=0; j<n; j++) {
pthread_join(t[j], (void **)&t_returnValue[j]);
}
first -= n;
for(int j=0; j<n; j++) {
printf("\n T%c: Times %d", (char)first++, (*t_returnValue)[j]);
}
return 0;
}
And this is the output:
ACEDBAEBDCAEDBEBADBADEADEADEEDDD TA: Times 6 TB: Times 65 TC: Times 4 TD: Times 66 TE: Times 1
Every time, the 2nd and 4th threads points to first char (?) and i cant see the error...