【发布时间】:2017-12-01 04:30:35
【问题描述】:
我需要对我的代码进行反馈以获取以下语句,我是否走在正确的道路上?
问题陈述:
一个。实现一个信号量类,它有一个私有 int 和三个公共方法: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;
}
【问题讨论】:
标签: c++ multithreading algorithm operating-system semaphore