#include "copyright.h"
#include "thread.h"
#include "list.h"
class Semaphore
{
public:
Semaphore(char* debugName, int initialValue); //设置信号量初值
~Semaphore(); //析构函数
char* getName() { return name; } //debugging assist
void P(); //waits until value > 0, then decrement
void V(); //increment, waking up a thread waiting in P() if necessary
//均为原子操作
private:
char *name; //useful for debugging
int value; //信号量的值,均为非负的
List *queue; //threads waiting in P() for the value to be >0
};
class Lock
{
public:
Lock(char* debugName); //initialize lock to be FREE
~Lock(); //析构函数
char* getName() { return name; } //debugging assist
void Acquire(); //wait until the lock is FREE, then set it to BUSY
void Release(); //set lock to be FREE, waking up a thread waiting
//均为原子操作
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
Thread *HoldThread;
bool Hold;
Semaphore *semaphore;
int threadnum;
};
class Condition
{
public:
Condition(char* debugName); //初始化条件变量为"no one waiting"
~Condition(); //析构函数
char* getName() { return name; } //debugging assist
void Wait(Lock *conditionLock); //release the lock, relinquish the CPU until signaled,
//then re-acquire the lock
//为原子操作
void Signal(Lock *conditionLock); //wake up a thread,
//if there are any waiting on the condition
void Broadcast(Lock *conditionLock);
//wake up all threads waiting on the condition
private:
char* name;
Semaphore *semaphore;
int threadnum;
};
- 1
- 2
前往页