Segmentation Fault (core dumped) in pthread_join

Viewed 49

I get an error of segmentation fault core dumped when running this script. The code has the option to choose the number of threads. Choosing 1 thread will not generate the error but picking nthread > 1 will cause the segmentation fault. I have spent quite some time debugging exactly where the error appears. The error originates in calling the worker function inside pthread_create. It seems to be occurring in the line below only for nthreads > 1:

ret = slevmar_bc_der(mesi_fun, mesi_jac, p, slice, 4, N_EXP, LB, UB, NULL, 1000, opts, NULL, NULL, NULL, NULL);

Here is the worker function that is passed as the 3rd argument to pthread_create

void * worker(void *arg) {

  int i, j, ret;
  float slice[N_EXP];
  float p[4];

  struct worker_param *param = (struct worker_param*) arg;

  for(i = param->start; i < param->stop; i++) {
    
    // Extract speckle variance (K^2) for each exposure at each index
    for(j = 0; j < N_EXP; j++){
      slice[j] = BUFFER[i + j * param->n] * BUFFER[i + j * param->n];
    }
    // Define initial parameter estimates
    p[0] = 0.15;
    if(slice[9] <= 0.01) {
      p[1] = 1.0;
      p[2] = 1.0E-5;
    } else {
      p[1] = 0.8;
      p[2] = 1.0E-3;
    }
    p[3] = 1.0E-2;

    ret = slevmar_bc_der(mesi_fun, mesi_jac, p, slice, 4, N_EXP, LB, UB, NULL, 1000, opts, NULL, NULL, NULL, NULL);
    // Write the values to the output
    for(j = 0; j < 4; j++)
      OUTPUT[param->output + j * param->n + i - param->start] = p[j];
  }

  pthread_exit(NULL);

}

This is how the functions mesi_fun is defined:

void mesi_fun(float *p, float *x, int m, int n, void *data) { <some code> }

Part of the main function is as follows. In the main function I call pthread_create and pthread_join()

for(j = 0; j < nthread; j++) {

  param[j] = malloc(sizeof(struct worker_param));

  param[j]->start = (n_pixels * N_EXP * i) + (n_pixels * j / nthread);

  if (j < nthread - 1)
    param[j]->stop = (n_pixels * N_EXP * i) + (n_pixels * (j + 1) / nthread);
  else
    param[j]->stop = (n_pixels * N_EXP * i) + n_pixels;

  param[j]->n = n_pixels;
  param[j]->output = (n_pixels * i * 4) + (n_pixels * j / nthread);

  pthread_create(&tid[j], NULL, &worker, (void*) param[j]);

}
// Wait for all threads to complete
for(j = 0; j < nthread; j++){
  pthread_join(tid[j], NULL);
}

Does anyone understand how exactly is pthread doing parallelization and how can I debug this code further. Thanks

I need help. As I said, its running as a single threaded application but not working as a multi threaded one. Are there alternate better ways for multi threaded packages for C that I can use if this can't work.

0 Answers
Related