Exercise 1 Using the synchronization primitives
In this exercise we chaged the writer-function from exercise 4 (see "Øvelse 4") .
We wanted to protect the function-call setAndTest().
First we used Mutex. We made a global variabel in the top of the cpp-file:
pthread_mutex_t my_mutex = PTHREAD_MUTEX_INITIALIZER;
And wrote the mutex-lock around the setAndTest-function call.
No errors are shown in the execution of the program (sometimes there were an error ind writing "Ingen fejl", because the mutex only protects the function-call).
sem_t my_semaphore;
In the beginning of the main-function we wrote:
sem_init(&my_semaphore, 0 , 30 ); // 0 to make a local semaphore
// 30 is the number of "takers" on the same time
In the end of the main-function we wrote:
sem_destroy(&my_semaphore); // to destroy the semaphore after ended process.
The writer program with semaphores:
Binary semaphore:
sem_init(&my_semaphore, 0, 1) // binary semaphore works like mutex
Exercise 2 Mutexes & Semaphores
A mutex is
owned by only one thread at a time.
A mutex can only be released by its taker.
A mutex can only be released by its taker.
Semaphores
are not owned by only one thread at a time. (Unless the semaphore is made
binary)
All the threads which work on the semaphore can release it.
All the threads which work on the semaphore can release it.
Exercise 3 Ensuring proper unlocking
ScopedLocker class (scopedLocker.h)
We make a object called my_lock of the type ScopedLocker.
This object is made inside a scope and destroyed when the scope has ended.
When the object is made, the constructor of ScopedLocker, locks the mutex.
When the object is destroyed, the destructor of ScopedLocker, unlocks the mutex.
The execution of the file shows no errors:
Exercise 4 On target
The execution of the file on the target:
The exercise revolves around solving the shared data problem, using either a semaphore or a mutex to do so. In addition to this it is about figuring out what the difference between semaphore and mutex is, in theory and practice.
SvarSletYou have solved the exercise greatly, and it shines through that you understand whats going on below surface.
If you have to pick out something, I dont find explanation on semaphores (ex.2) totally clear.
It might be worth noting that a fixed amount of threads can use a semaphore before locking and not just everyone.