次のステートメントのために私のコードにフィードバックが必要ですが、私は正しいパスですか?Peterson's Nプロセスアルゴリズムを使用したセマフォーの実装
問題文:
a。プライベートintと3つのパブリックメソッド(init、wait、signal)を持つセマフォークラスを実装します。 waitメソッドとsignalメソッドは、セマフォから期待どおりに動作する必要があり、実装にはPetersonのNプロセスアルゴリズムを使用する必要があります。
b。共有整数の値を同時に更新する5つのスレッドを作成し、パートa)で作成したセマフォクラスのオブジェクトを使用して同時更新の正確性を保証するプログラムを作成します。待ちループで回転させながら、あなたがミューテックスを解放する必要が
#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;
}
コードを表示することは可能でしょうか? – June