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?
#include <iostream>
#include <pthread.h>
#include <vector>
#include <cstdlib>
#include <stdlib.h>
#include <stdio.h>
#include <pthread.h>
#include <semaphore.h>
#include <string.h>
#include <unistd.h>
#define BUFFER_SIZE 10
void *Produce(void *);
void *Consume(void *);
int InsertItem(int);
int RemoveItem(int *);
int iCounter;
pthread_mutex_t mutex;
sem_t full, empty;
std::vector<int> buffer(BUFFER_SIZE);
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" ;}
sleep(5);
delete [] aa;
delete [] bb;
for (int j=0;j<iCounter;j++)
// cout<<buffer[j];
return 0;
}
void * Produce(void * Param)
{
int item;
for (int i=0;i<5;i++)
{
int t = rand() % 1000;
usleep(t);
item = rand() % 100;
sem_wait(&empty);
pthread_mutex_lock(&mutex);
int iMsg = InsertItem(item);
if(iMsg == -1){
printf("Error Inserting Item \n");
}else
{
printf("Produced Item :: %d Thread No :: %d\n", item , *((int *)Param));
}
pthread_mutex_unlock(&mutex);
sem_post(&full);
}
}
void * Consume(void * Param)
{
int item;
while(1)
{
int t = rand() % 1000;
usleep(t);
sem_wait(&full);
pthread_mutex_lock(&mutex);
int iMsg = RemoveItem(&item);
if(iMsg == -1){
printf("Error Removing Item \n");
}else
{
printf("Consumed Item :: %d Thread No :: %d \n", item ,*((int *)Param));
}
pthread_mutex_unlock(&mutex);
sem_post(&empty);
}
}
int InsertItem(int item)
{
if(iCounter < BUFFER_SIZE)
{
buffer.push_back (item);
iCounter++;
return 1;
}
else{
return -1;
}
}
int RemoveItem(int *item)
{
if(iCounter > 0)
{
*item = buffer[0];
buffer.erase (buffer.begin());
iCounter--;
return 1;
}
else{
return -1;
}
}
Aucun commentaire:
Enregistrer un commentaire