I got to use threads to solve a given problem, the only thing I need to do is make somehow that my threads use a function called launchR, I tested my function using no threads and runs ok, but whenever I try messing with threads I get segmentation fault and I cannot find the reason. This is how I handle my threads:
pthread_t threads[n];
int rc, t;
int *tid[n];
int bpt = b/n,
macc = b%n,
adv = 0;
for (t=0; t < n; t++) {
tid[t] = (int *)malloc(sizeof(int));
*tid[t] = t;
printf("Creando el Hilo %d\n",t);
if (macc == 0 ) {
rc = pthread_create(&threads[t],NULL,launchR(objarr,bombs,adv,obj,bpt), (void *)tid[t]);
printf("\n Cree el Hilo THID: %d \n",*(tid[t]));
if (rc) {
printf("Error, %d\n",rc);
exit(-1);
}
adv=adv+bpt;
}
else if (macc > 0 ) {
rc = pthread_create(&threads[t],NULL,launchR(objarr,bombs,adv,obj,bpt+1), (void *)tid[t]);
printf("\n Cree el Hilo THID: %d \n",*(tid[t]));
if (rc) {
printf("Error, %d\n",rc);
exit(-1);
}
adv=adv+bpt+1;
printf("%d\n", adv);
}
macc--;
}
for (t=0; t < n; t++) {
pthread_join(threads[t],NULL);
}
I would appreciate any advice you could give me.
Edit: here's the code for the function launch, it's based on another function.
void launch ( int obj[][5] , int bombs[][4] , int bomb, int objs ) {
for (int i = 0; i < objs; ++i) {
if ( obj[i][0] <= (bombs[bomb][0] + bombs[bomb][2]) &&
obj[i][0] >= (bombs[bomb][0] - bombs[bomb][2]) &&
obj[i][1] <= (bombs[bomb][1] + bombs[bomb][2]) &&
obj[i][1] >= (bombs[bomb][1] - bombs[bomb][2])){
if (obj[i][3] == 1) {
obj[i][2] = obj[i][2] - bombs[bomb][2];
obj[i][4] = 1;
}
else if (obj[i][3] == -1){
obj[i][2] = obj[i][2] + bombs[bomb][2];
obj[i][4] = 1;
}
}
}
}
void *launchR(int obj[][5] , int bombs[][4] , int ibomb, int objs, int cant){
for (int i = ibomb; i <= cant; i++) {
launch(obj,bombs,i,objs);
}
}
Edit 2: Here is my output:
entro en threads
Creando el Hilo 0
Cree el Hilo THID: 0
2
Creando el Hilo 1
[1] 19677 segmentation fault ./batalla -t -n 3 prueba