precision
precision

Reputation: 303

Reason behind segmentation fault in multithreaded program

The following program stops because of segmentation fault. When I tried to debug it, it shows

 Program received signal SIGSEGV, Segmentation fault.
[Switching to Thread 0x7ffff6ff4700 (LWP 7293)]
0x0000000000400a79 in do_work(void*) ()
(gdb) bt
#0  0x0000000000400a79 in do_work(void*) ()
#1  0x00007ffff7bc4182 in start_thread (arg=0x7ffff6ff4700)
    at pthread_create.c:312
#2  0x00007ffff78f0fbd in clone ()
    at ../sysdeps/unix/sysv/linux/x86_64/clone.S:111

The program is as follows:

#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <cstring>
#include <unistd.h>
#include <ctime>

#define NTHREADS 3
#define iter 10
#define max_key 3 
pthread_mutex_t lock[max_key];

void *do_work(void *tid) 
{
  int i, start, *mytid, end,rank,len,key;
  double lock_var;
  mytid = (int *) tid; //edit: suggested by Eric Tsui; It fixed the problem
  for (i=0; i<iter; i++){ 
  lock_var=(double)rand() / (double)RAND_MAX ;
  if (lock_var<=0.5){ 
    key = 0; 
  }
  else if ((lock_var>0.5)&&(lock_var<=0.9)){ 
    key = 1;
  }
  else {
    key = 2; 
  } 
  pthread_mutex_lock (&lock[key]);
  printf("I'm:%d with key:%d\n",*mytid,key);
  sleep(1);
  pthread_mutex_unlock (&lock[key]);

 }
 pthread_exit(NULL);
}



int main(int argc, char *argv[])
{
  int i, start, tids[NTHREADS];
  pthread_t threads[NTHREADS];
  pthread_attr_t attr;
  srand(time(NULL));  
  for (i=0;i<max_key;i++){ 
  pthread_mutex_init(&lock[i], NULL);
  }
  pthread_attr_init(&attr);  
  pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
  for (i=0; i<NTHREADS; i++) {
    tids[i] = i;
    pthread_create(&threads[i], &attr, do_work, (void *) &tids[i]);
    }
  for (i=0; i<NTHREADS; i++) {
    pthread_join(threads[i], NULL);
  }

  printf ("Done\n");
  pthread_attr_destroy(&attr);
  for (i=0;i<max_key;i++){ 
  pthread_mutex_destroy(&lock[i]);
  }
  pthread_exit (NULL);

}

I checked the code but unable to find the reason for segmentation fault. Could anyone please let me know the reason behind segmentation fault in this code.

Upvotes: 0

Views: 2718

Answers (1)

Eric Tsui
Eric Tsui

Reputation: 1924

The myid in do_work func is supposed to be assigned with input tid,

void *do_work(void *tid) 
{
  int i, start, *mytid, end,rank,len,key;
  double lock_var;
  mytid = (int *) tid; //edit: suggested by Eric Tsui; It fixed the problem
  for (i=0; i<iter; i++){ 
  lock_var=(double)rand() / (double)RAND_MAX ;
  if (lock_var<=0.5){ 
    key = 0; 
  }
  else if ((lock_var>0.5)&&(lock_var<=0.9)){ 
    key = 1;
  }
  else {
    key = 2; 
  } 
  pthread_mutex_lock (&lock[key]);
  printf("I'm:%d with key:%d\n",*mytid,key);
  sleep(1);
  pthread_mutex_unlock (&lock[key]);

 }
 pthread_exit(NULL);
}

Upvotes: 1

Related Questions