OS1/Modifikacije predrok 2019

Izvor: SI Wiki
Pređi na navigaciju Pređi na pretragu
Ovaj rok nije rešen. Pomozite SI Wiki tako što ćete ga rešiti.

Sledeće modifikacije su se pojavile na odbrani projekta u predroku 2019.

20 poena

  • Proširiti klasu Semaphore statičkom metodom addOwner() i nestatičkom metodom removeOwner(ID id) koje dodaju i uklanjaju vlasnike semafora, respektivno.
  • addOwner() dodaje tekuću nit kao vlasnika. removeOwner(ID id) uklanja nit sa zadatim ID-jem ukoliko je ona bila vlasnik.
  • Ukoliko metode wait() ili signal() pozove nit koja ne pripada skupu vlasnika, one nemaju efekta.

Rešenje

Primer testa.

#include "thread.h"
#include "intLock.h"
#include "semaphor.h"

Semaphore sem(1);

class testThread : public Thread {
public:
    testThread(int i) : Thread() { this->ind = i; }
    ~testThread() { waitToComplete(); }

protected:
    void run() {
        if (ind % 2) sem.addOwner();
        while (1) {
            if (sem.wait(0) != -1) {
                intLock
                printf("%d Usao u kriticnu sekciju\n", ind);
                intUnlock
                
                sem.signal();

                intLock
                printf("%d Izasao iz kriticne sekcije\n", ind);
                intUnlock

                sem.removeOwner(Thread::getRunningId());
            }
            else break;
        }
    }

private:
    int ind;
};

void tick() {}

const int N = 20;

int userMain(int argc, char* argv[]) {
    testThread *thrs[N];

    for (int i = 0; i < N; i++) {
        thrs[i] = new testThread(i);
        thrs[i]->start();
    }
    for (int j = 0; j < N; j++) {
        delete thrs[j];
    }
    printf("Kraj!\n");
}