简体   繁体   English

pthread_join分段错误

[英]pthread_join Segmentation fault

I am trying to use pthread_join with this producer-consumer program but I keep getting a segmentantion fault. 我正在尝试将pthread_join与该生产者-消费者程序一起使用,但是我不断遇到分段错误。 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_join()的参数是存储在pthread_create()的第一个参数中的值。

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

The thread handle is the pthread_t t handle. 线程句柄是pthread_t t句柄。 What did you do with it? 你是怎么做的? You threw it away, and you are passing the aa[i] parameter to pthread_join(). 您将其丢弃,然后将aa[i]参数传递给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(). 您需要保存pthread_t句柄, 就是传递给pthread_join()的内容。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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