Idle waiting

Arquivo:

Solução:

Para a solução do exercício foram utilizados listeners. Cada Thread tem uma lista de listeners que permanecem suspensos enquanto a Thread está em execução e são acordados durante a execução do método exit() da Thread sendo ouvida.

Thread * old = _running;
// Waking up listeners
Thread * temp;
if (!old->_listeners.empty()) {
   for (unsigned int i=0;i<old->_listeners.size();i++ ) {
      temp = old->_listeners.remove()->object();
      temp->resume();
   }
}

Abaixo segue o trecho de código responsável pelo cadastro de uma Thread como listener de outra.

int Thread::join() {
   db(TRC) << "Thread::join(this=" << this
   << ",state=" << _state << ")\n";

   if(_state != FINISHING) {
      // Add the current Thread being executed as listener of this Thread to be
      // waked up at the end of this Thread execution.
      _listeners.insert(&_running->_link);
      _running->suspend();
   }

   return *((int *)_stack);
}

E a declaração do atributo _listener em Thread.h.

#include <utility/list.h>
...
List<Thread> _listeners;