1

I am trying to use pthread_join with this producer-consumer program but I keep getting a segmentantion fault. My purpose is to wait for all the producer threads to end and then terminate all the consumers. But after the first thread joins I get a segmentation fault. I searched the web but haven't found anything useful. Any Ideas?

using namespace std ;
int main()
{
  pthread_mutex_init(&mutex , NULL);
 sem_init(&full , 0 ,0);
 sem_init(&empty , 0 , BUFFER_SIZE);
  pthread_t ProducerThread , ConsumerThread;

 int *aa = new int [4];
 for(int i = 0 ; i < 4 ; i++)
 {
  aa[i] = i;
  pthread_t t;
  int k= pthread_create(&t , NULL, Produce , &aa[i]);
  if(k!=0)
  cout<<"Errot"<<endl;
  else  
  printf("Creating Producer %d \n", i);
 }
 int *bb = new int[2];
 for(int i = 0 ; i < 2 ; i++)
 {
  bb[i] = i;
  pthread_t t;
  pthread_create(&t , NULL, Consume , &bb[i]);
  printf("Creating Consumer %d \n", i);
 }
int s;
  for (int i=0;i<4;i++){
  s = pthread_join(aa[i],NULL);
               if (s != 0)
                   cout<< "pthread_join error" ;}
makripx
  • 35
  • 5
  • 1
    Do you get any specific errors? Could you paste the specific code? Makes it easier for other people to follow. – Bono Mar 02 '15 at 00:57
  • This is far from a minimal sample, as required for a valid question here. Reduce your code, until it just reproduces the behavior you're asking about. – πάντα ῥεῖ Mar 02 '15 at 00:59
  • I get the "Segmentation fault (core dumped)" error. The error occurs when I add the "s = pthread_join(aa[i],NULL);" line ^^ – makripx Mar 02 '15 at 01:02
  • @makripx _"The error occurs when I add the "s = pthread_join(aa[i],NULL);"_ And you can't just show this in a minimal context, without all of the other irrelevant code?? – πάντα ῥεῖ Mar 02 '15 at 01:08
  • I apologize. It's my first post. I edited my question and I will try to be more to the point the next time. – makripx Mar 02 '15 at 01:16

1 Answers1

5

The argument to pthread_join() is the value that was stored in pthread_create()'s first argument.

pthread_t t;
int k= pthread_create(&t , NULL, Produce , &aa[i]);

The thread handle is the pthread_t t handle. What did you do with it? You threw it away, and you are passing the aa[i] parameter to pthread_join().

Which is not the thread handle.

You need to save the pthread_t handle, and that is what's passed to pthread_join().

Sam Varshavchik
  • 114,536
  • 5
  • 94
  • 148