简体   繁体   中英

pthread_join Segmentation fault

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" ;}

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().

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM