os practical-presentation

5
Emmanuel Alejandro García Solís - 1450138 Maximiliano Hernández Castillo - 1453557 Adán de Jesús Silva Cuéllar - 1462847

Upload: emmanuel-garcia

Post on 21-Jul-2015

482 views

Category:

Education


0 download

TRANSCRIPT

Page 1: Os practical-presentation

Emmanuel Alejandro García Solís - 1450138

Maximiliano Hernández Castillo - 1453557

Adán de Jesús Silva Cuéllar - 1462847

Page 2: Os practical-presentation

Lock::Lock(const char* debugName) {name = debugName;semaphore = new Semaphore("lock", 1);lockHolder = NULL;

}

Lock::~Lock() {delete semaphore;

}

void Lock::Acquire() {semaphore->P();lockHolder = currentThread;

}

class Lock { public:

Lock(const char*debugName); ~Lock(); void Acquire(); void Release(); bool IsHeldByCurrentThread() bool tryAcquire();

private: const char* name;Thread *lockHolder; Semaphore *semaphore;

};

Page 3: Os practical-presentation

class Lock { public:

Lock(const char*debugName); ~Lock(); void Acquire(); void Release(); bool IsHeldByCurrentThread() bool tryAcquire();

private: const char* name;Thread *lockHolder; Semaphore *semaphore;

};

bool Lock::IsHeldByCurrentThread(){

return lockHolder == currentThread;

}

void Lock::Release() {

ASSERT(IsHeldByCurrentThread());

lockHolder = NULL;

semaphore->V();

}

bool Lock::tryAcquire(){

if(lockHolder == NULL){

semaphore->P();

lockHolder = currentThread;

return true;

}

else{

return false;

}

}

/*Almost the same than Acquire(), except that, if

someone has the lock, it will return immediately

instead of waiting*/

Page 4: Os practical-presentation

Condition::Condition(const char* debugName, Lock* conditionLock){

name = debugName;

waitQueue = new List<Semaphore *>;

}

void Condition::Wait(Lock *conditionLock) {

Semaphore *waiter;

ASSERT(conditionLock>IsHeldByCurrentThread());

waiter = new Semaphore("condition", 0);

waitQueue->Append(waiter);

conditionLock->Release();

waiter->P();

conditionLock->Acquire();

delete waiter;

}

/*Queue containing allocated

Semaphores for each waiting thread*/

/*

1. Checks if the current thread has the lock.

2. Creates a semaphore, initially 0.

3. Adds the semaphore to the queue.

4. Releases the lock, and goes to sleep until

someone sends a Signal.

5. When someone sends a Signal, reaquires the

lock and deletes the semaphore*/

Page 5: Os practical-presentation

void Condition::Signal(Lock *conditionLock) {

Semaphore *waiter;

ASSERT(conditionLock->IsHeldByCurrentThread());

if(!waitQueue->IsEmpty()){

waiter = waitQueue->Remove();

waiter->V();

}

}

void Condition::Broadcast(Lock *conditionLock) {

while(!waitQueue->IsEmpty()){

Signal(conditionLock);

}

}

/*Checks if the the current thread

has the lock*/

/*If it’s true, removes the last semaphore from the

wait queue, assigns it to the waiter semaphore,

and calls V, to wake him up*/

/* Wake up all threads waiting on this condition

until the wait queue is empty*/