Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include "thread.h"
- #include "semaphore.h"
- #include <stdio.h>
- #include "intlock.h"
- #include "assert.h"
- #define N 5
- #define THINKING 2
- #define HUNGRY 1
- #define EATING 0
- #define LEFT (phnum + 4) % N
- #define RIGHT (phnum + 1) % N
- int state[N];
- int treshold = 10000;
- #define ASSERT
- Semaphore mutex(1); //moguca greska??
- Semaphore* S[N];
- void test(int phnum)
- {
- if (state[phnum] == HUNGRY
- && state[LEFT] != EATING
- && state[RIGHT] != EATING) {
- // state that eating
- state[phnum] = EATING;
- sleep(2);
- intLock
- std::cout << "Philosopher " << phnum + 1 << " takes fork " << LEFT + 1 << " and " << phnum + 1 << std::endl;
- std::cout << "Philosopher " << phnum + 1 << " is Eating\n";
- intUnlock
- //Nije doslo do toga da je neki semafor probio i usao u ovo cudo ovde
- //Jedino kako radim sinhronizaciju jeste preko testiranja mog levog i desnog suseda
- #ifdef ASSERT
- sleep(200); //sleep for 200ms;
- assert(state[LEFT] != EATING && state[RIGHT] != EATING);
- #endif //ASSERT
- S[phnum]->signal();
- }
- }
- void take_fork(int phnum)
- {
- mutex.wait();
- // state that hungry
- state[phnum] = HUNGRY;
- intLock
- std::cout << "Philosopher " << phnum + 1 << " is Hungry\n";
- intUnlock
- // eat if neighbours are not eating
- test(phnum);
- mutex.signal();
- S[phnum]->wait();
- sleep(1);
- }
- // put down chopsticks
- void put_fork(int phnum)
- {
- mutex.wait();
- // state that thinking
- state[phnum] = THINKING;
- intLock
- std::cout << "Philosopher " << phnum + 1 << " putting fork " << LEFT + 1 << " and " << phnum +1 << " down\n";
- std::cout << "Philosopher " << phnum +1 << " is thinking\n";
- intUnlock
- test(LEFT);
- test(RIGHT);
- mutex.signal();
- }
- void* philospher(void num)
- {
- int k = 0;
- while(k++ < treshold) {
- int i = num;
- sleep(1);
- take_fork(i);
- sleep(0);
- put_fork(i);
- }
- }
- class Philosopher::public Thread{
- public:
- Philosopher(int i) { num = i; }
- virtual ~Philosopher() {
- waitForComplete();
- }
- protected:
- void run() { philosopher(num); }
- private:
- int num;
- }
- void tick()
- {
- }
- int userMain()
- {
- Thread* threads[N];
- for (i = 0; i < N; i++)
- S[i] = new Semaphore(0);
- for (i = 0; i < N; i++) {
- threads[i] = new Philosopher(i);
- threads[i].start();
- intLock
- std::cout << "Philosopher "<< i + 1 << " is thinking\n";
- intUnlock
- }
- for (i = 0; i < N; i++)
- threads[i]->waitForComplete();
- for (i = 0; i < N; i++)
- delete S[i];
- for (i = 0; i < N; i++)
- delete Philosopher(i);
- std::cout << "Test passed!\n";
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement