From d1d3714b63876a0bcb9b3b97f33d3e967f1d0420 Mon Sep 17 00:00:00 2001 From: ChUrl Date: Sat, 16 Jul 2022 00:58:59 +0200 Subject: [PATCH] update preemption demo to variable thread num --- c_os/user/demo/PreemptiveThreadDemo.cc | 27 ++++++++++++++------------ c_os/user/demo/PreemptiveThreadDemo.h | 4 +++- 2 files changed, 18 insertions(+), 13 deletions(-) diff --git a/c_os/user/demo/PreemptiveThreadDemo.cc b/c_os/user/demo/PreemptiveThreadDemo.cc index 0aee661..105fb8c 100644 --- a/c_os/user/demo/PreemptiveThreadDemo.cc +++ b/c_os/user/demo/PreemptiveThreadDemo.cc @@ -2,34 +2,37 @@ void PreemptiveLoopThread::run() { int cnt = 0; + while (true) { // Basic synchronization by semaphore sem->p(); - kout.setpos(55, this->id); - kout << this->id << ": " << dec << cnt++ << endl; + // Saving + restoring kout position doesn't help much as preemption still occurs, + // only LoopThreads are synchronized, so other output will be disturbed sometimes + // kout.setpos(55, this->id); + // kout << fillw(3) << this->id << fillw(0) << ": " << dec << cnt++ << endl; sem->v(); } } void PreemptiveThreadDemo::run() { - kout << "PreemptiveThreadDemo ====================================" << endl; kout << "Initializing Semaphore" << endl; Semaphore* sem = new Semaphore(1); // Create this semaphore on the heap as this thread exits itself, // so stack allocated objects will be lost - kout << "Allocating LoopThread A" << endl; - Thread* cntA = new PreemptiveLoopThread(0, sem); - kout << "Allocating LoopThread B" << endl; - Thread* cntB = new PreemptiveLoopThread(1, sem); - kout << "Allocating LoopThread C" << endl; - Thread* cntC = new PreemptiveLoopThread(2, sem); + // TODO: Threads disappear, the fewer loop the faster they vanish + // It seems like this happens with exactly 3 or 4 loopthreads + Thread* threads[this->number_of_threads]; + kout << "Allocating LoopThreads" << endl; + for (unsigned int i = 0; i < this->number_of_threads; ++i) { + threads[i] = new PreemptiveLoopThread(i, sem); + } kout << "Adding threads to ready queue" << endl; - scheduler.ready(cntA); - scheduler.ready(cntB); - scheduler.ready(cntC); + for (unsigned int i = 0; i < this->number_of_threads; ++i) { + scheduler.ready(threads[i]); + } kout << "Exiting main thread" << endl; scheduler.exit(); diff --git a/c_os/user/demo/PreemptiveThreadDemo.h b/c_os/user/demo/PreemptiveThreadDemo.h index a4e7520..474219e 100644 --- a/c_os/user/demo/PreemptiveThreadDemo.h +++ b/c_os/user/demo/PreemptiveThreadDemo.h @@ -24,8 +24,10 @@ class PreemptiveThreadDemo : public Thread { private: PreemptiveThreadDemo(const PreemptiveThreadDemo& copy) = delete; // Verhindere Kopieren + unsigned int number_of_threads; + public: - PreemptiveThreadDemo() { + PreemptiveThreadDemo(unsigned int n) : number_of_threads(n) { kout << "Initialized PreemptiveThreadDemo" << endl; }