Demo entry 6677994

synch.h

   

Submitted by anonymous on Dec 05, 2017 at 02:44
Language: C++. Code size: 2.2 kB.

#ifndef SYNCH_H
#define SYNCH_H

#include "copyright.h"
#include "thread.h"
#include "list.h"

//#define semaphore


class Semaphore {
  public:
    Semaphore(char* debugName, int initialValue);	// set initial value
    ~Semaphore();   					// de-allocate semaphore
    char* getName() { return name;}			// debugging assist
    
    void P();	 // these are the only operations on a semaphore
    void V();	 // they are both *atomic*
    
  private:
    char* name;        // useful for debugging
    int value;         // semaphore value, always >= 0
    List *queue;       // threads waiting in P() for the value to be > 0
};
 
#ifdef semaphore
class Lock {
  public:
    Lock(char* debugName);  		// initialize lock to be FREE
    ~Lock();				// deallocate lock
    char* getName() { return name; }	// debugging assist

    void Acquire(); // these are the only operations on a lock
    void Release(); // they are both *atomic*

    bool isHeldByCurrentThread();	// true if the current thread
					// holds this lock.  Useful for
					// checking in Release, and in
					// Condition variable ops below.

  private:
    char* name;				// for debugging
    Semaphore *lockSemaphore;
    Thread * heldThread;
// plus some other stuff you'll need to define
};

#else

class Lock{
public:
Lock(char *debugName);
~Lock();
char *getName(){return name;}
void Acquire();
void Release();
bool isHeldByCurrentThread();
private:
char *name;
int value;
List *queue;
Thread *heldThread;
};
#endif

class Condition {
  public:
    Condition(char* debugName);		// initialize condition to 
					// "no one waiting"
    ~Condition();			// deallocate the condition
    char* getName() { return (name); }
    
    void Wait(Lock *conditionLock); 	// these are the 3 operations on 
					// condition variables; releasing the 
					// lock and going to sleep are 
					// *atomic* in Wait()
    void Signal(Lock *conditionLock);   // conditionLock must be held by
    void Broadcast(Lock *conditionLock);// the currentThread for all of 
					// these operations

  private:
    char* name;
    List *waitQueue;
    // plus some other stuff you'll need to define
};
#endif // SYNCH_H

This snippet took 0.01 seconds to highlight.

Back to the Entry List or Home.

Delete this entry (admin only).