I3ISU_Opgave5

Exercise 1 Mutex and/or Semaphore
We are using mutex in our solution, because we only want one owner, to modify the data at the time. If we used semaphores, multiple threads would be able to change our data, and compromise the shared data.

Exercise 2 Using the synchronization primitive
Data: code format="cpp" pthread_mutex_t mutex1 = PTHREAD_MUTEX_INITIALIZER;

int shared = 0;

void *reader(void*) {   for(int i = 0; i < 10; i++) {   pthread_mutex_lock(&mutex1); printf("Current shared value: %d\n", shared); pthread_mutex_unlock(&mutex1); sleep(1); } }

void *incrementer(void*) {   for(int i = 0; i < 10; i++) {   pthread_mutex_lock(&mutex1); shared++; pthread_mutex_unlock(&mutex1); sleep(1); }   pthread_exit(NULL); }

code Sharing vector class: code format="cpp" pthread_mutex_t mutex1 = PTHREAD_MUTEX_INITIALIZER;

const int thread_number = 100; Vector vec1;

void* writer(void* id) {

for(int i = 1; i < 101; i++) {       pthread_mutex_lock(&mutex1); if(!vec1.setAndTest(i)) printf("Error found. Thread: %d, i: %d\n", (int)id, i); else printf("No Error found. Thread:%d, i:%d\n", (int)id, i); pthread_mutex_unlock(&mutex1); usleep(10); }   pthread_exit(NULL); } code When we run the program, we can see that there are no errors. We fixed the problems, by inserting mutexes, to protect the data. Link to .cpp file for Data sharing and Vector sharing.

Exercise 3 Ensuring proper unlocking
code format="cpp"
 * 1) pragma once
 * 2) include 

class scopedLocker { public: scopedLocker(pthread_mutex_t * mutex) {       mutex_ = mutex; pthread_mutex_lock(mutex_); }

~scopedLocker {       pthread_mutex_unlock(mutex_); }

private: pthread_mutex_t * mutex_; };

code This is our scope locker. It gets a pointer to the mutex, in the constructor, keeps it for its duration, and releases the mutex in the deconstructor. This prevents, forgetting releasing the mutex, and it will also automatic release the mutex, when the class is destroyed.

In our Vector.hpp we also make a few changes. code format="cpp" bool setAndTest(int n) { scopedLocker lockResource(&mutex); // Init for our scope lock. set(n); return test(n); } code Our mutex have been moved to member data of the Vector class, and will be initialized in the Vector constructor. Link to source code.

When running the program without the use of scopedLocker (Out commenting the line), we get multiple errors. If we run the program with scopedLocker, there are no errors.

Exercise 4 On target
We compiled the program for the target, and while running, we experienced no problems in this process.