Ich brauche Feedback zu meinem Code für folgende Aussage, bin ich auf dem richtigen Weg?Eine Semaphor-Implementation mit Petersons N-Prozess-Algorithmus
Problemstellung:
a. Implementieren Sie eine Semaphor-Klasse mit einem privaten int und drei öffentlichen Methoden: init, wait und signal. Die Warte- und Signalmethoden sollten sich wie von einem Semaphor erwartet verhalten und müssen bei ihrer Implementierung den Petersonschen N-Prozessalgorithmus verwenden.
b. Schreiben Sie ein Programm, das 5 Threads erstellt, die gleichzeitig den Wert einer gemeinsamen Ganzzahl aktualisieren, und verwenden Sie ein Objekt der Semaphor-Klasse, das in Teil a) erstellt wurde, um die Korrektheit der gleichzeitigen Aktualisierungen sicherzustellen.
Hier ist mein Arbeitsprogramm:
#include <iostream>
#include <pthread.h>
using namespace std;
pthread_mutex_t mid; //muted id
int shared=0; //global shared variable
class semaphore {
int counter;
public:
semaphore(){
}
void init(){
counter=1; //initialise counter 1 to get first thread access
}
void wait(){
pthread_mutex_lock(&mid); //lock the mutex here
while(1){
if(counter>0){ //check for counter value
counter--; //decrement counter
break; //break the loop
}
}
pthread_mutex_unlock(&mid); //unlock mutex here
}
void signal(){
pthread_mutex_lock(&mid); //lock the mutex here
counter++; //increment counter
pthread_mutex_unlock(&mid); //unlock mutex here
}
};
semaphore sm;
void* fun(void* id)
{
sm.wait(); //call semaphore wait
shared++; //increment shared variable
cout<<"Inside thread "<<shared<<endl;
sm.signal(); //call signal to semaphore
}
int main() {
pthread_t id[5]; //thread ids for 5 threads
sm.init();
int i;
for(i=0;i<5;i++) //create 5 threads
pthread_create(&id[i],NULL,fun,NULL);
for(i=0;i<5;i++)
pthread_join(id[i],NULL); //join 5 threads to complete their task
cout<<"Outside thread "<<shared<<endl;//final value of shared variable
return 0;
}
ist es möglich, Sie Code anzeigen? – June