So, I am working on a scheduler in one of my classes. Basically, we are pretending that only one thread can be executing at a time. We are supposed to use a semaphore class to allow these threads to block themselves to simulate the thread waiting for the CPU.
The problem is, the threads seem to block at the wrong time and execute at the wrong time. I was wondering if I am missing some conceptual understanding of a semaphore and how to implement it. I was wondering if I could get some feedback on my implementation. The instructor provided this header file which I have not modified in any way:
class Semaphore {
private:
int value;
pthread_mutex_t m;
pthread_cond_t c;
public:
/* -- CONSTRUCTOR/DESTRUCTOR */
Semaphore(int _val);
//~Semaphore();
/* -- SEMAPHORE OPERATIONS */
int P();
int V();
};
This is my implementation using posix stuff:
Semaphore::Semaphore(int _val){
value = _val;
c = PTHREAD_COND_INITIALIZER;
m = PTHREAD_MUTEX_INITIALIZER;
}
int Semaphore::P(){
if(value <= 0){
pthread_cond_wait(&c, &m);
}
value--;
}
int Semaphore::V(){
value++;
if(value > 0){
pthread_cond_signal(&c);
}
}