다음 코드는 내 코드에 대한 피드백이 필요합니다. 올바른 경로에 있습니까?Peterson의 N 프로세스 알고리즘을 사용하는 세마포어 구현
문제 설명 :
a. private int와 세 개의 public 메소드 인 init, wait 및 signal을 가진 세마포어 클래스를 구현하십시오. wait 및 signal 메소드는 세마포어에서 예상대로 작동해야하며 구현시 Peterson의 N 프로세스 알고리즘을 사용해야합니다.
b. 동시 업데이트의 정확성을 보장하기 위해 공유 정수의 값을 동시에 업데이트하고 부분 a)에서 만든 세마포어 클래스의 객체를 사용하는 5 개의 스레드를 만드는 프로그램을 작성하십시오. 대기 루프에서 회전하는 동안이 뮤텍스를 해제 할 필요가
#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