This code is for Consumer Producer problem so i created Buffer class which is contain an array to store the data then i create two method one for conumer and producer the problem is when i want to deal with the thread i faced the error which is (argument of type "void *" is incompatible with parameter of type "void ()(void *)") i did understand it what i should to do! , Can any one help me please ?
#include <unistd.h>
#include <iostream>
#include <pthread.h>
#include <semaphore.h>
#include <time.h>
#include <stdlib.h>
#include<thread>
using namespace std;
#define BUFFER_CAPACITY 10
sem_t Empty;
sem_t Full;
pthread_mutex_t mutex;
class Buffer {
int buffer [BUFFER_CAPACITY];
int produced_index; // index
int consumed_index; // index
public:
Buffer(){
this->consumed_index=0;
this->produced_index=0;}
void *producer(void *pno){ // to produce data to the buffer []
srand(time(NULL));
int item;
while(true){
item = 1 + rand() % 100;
sem_wait(&Empty);
pthread_mutex_lock(&mutex);
usleep(50000 * 10);
buffer[produced_index] = item;
cout << "Producer " << *((int *)pno)<< ": Insert Item " << buffer[produced_index] << " at " << produced_index << endl;
produced_index = (produced_index + 1) % BUFFER_CAPACITY;
pthread_mutex_unlock(&mutex);
sem_post(&Full);}
void* VOID;
return VOID;
}
void *counsumer(void *pno){ // to take the data from the buffer
while(true){
sem_wait(&Full);
pthread_mutex_lock(&mutex);
usleep(100000 * 10);
int item = buffer[consumed_index];
cout << "Consumer " << this->id << ": Remove Item " << item << " from " << consumed_index << endl;
consumed_index = (consumed_index + 1) % BUFFER_CAPACITY;
pthread_mutex_unlock(&mutex);
sem_post(&Empty);
}
void* VOID;
return VOID;}};
int main(){
Buffer buf; // Create buffer
pthread_mutex_init(&mutex, NULL);
sem_init(&Empty,0,BUFFER_CAPACITY);
sem_init(&Full,0,0);
pthread_t pro[5],con[5];
int a[5] = { 1, 2, 3, 4, 5 };
for(int i = 0; i < 5; i++) pthread_create(&pro[i], NULL, buf.producer(), (void *)&a[i]);
for(int i = 0; i < 5; i++){ pthread_create(&con[i], NULL, buf.counsumer(), (void *)&a[i]); }
for(int i = 0; i < 5; i++){ pthread_join(pro[i], NULL); }
for(int i = 0; i < 5; i++){ pthread_join(con[i], NULL); }
pthread_mutex_destroy(&mutex);
sem_destroy(&Empty);
sem_destroy(&Full);}
so can any one help me to dealing with synchronization
Aucun commentaire:
Enregistrer un commentaire