Øvelse+04.1+-+Thread+synchronization

Exercise 1:
Which type of mutex or semaphore is the correct one to use to solve the problems in Lab Exercise 3?

Vi har valgt at bruge Mutex, da der kun er 1 tråd der skal pille ved vores vektor object.

Exercise 2:
Modify your program from Lab Exercise 3.2-3 and 3.2-4 to create and use a mutex or semaphore of the type determined above so that the shared resource is accessed atomically. Does it work?

Vi fik implamenteret vores mutex i vores øvelse og det virkede som det skulle

//pthread_mutex_t m;//

//pthread_mutex_lock(m);// //!!// //!!Vores kode// //!!// pthread_mutex_unlock(m);

Det virkede som det skulle, og vi kunne have 100 tråede til at køre, uden der var nogle af dem der failede!//

Exercise 3:
Exercise 3: The method for data protection in Lab Exercise 2 has one problem: The programmer is not forced to release the mutex/semaphore after he updates the shared data. Using the Scoped Locking idiom can enforce this. The idea behind the scoped locking idiom is that you create a class ScopedLocker which is passed a Mutex on construction. The ScopedLocker takes the Mutex object in its constructor and holds it until its destruction – thus, it holds the mutex as long as it is in scope. Implement the class ScopedLocker and use it in class Vector to protect the resource. Then run Exercise 2 again. Test your program – do you have any sharing problems now?

Vi fjerner lock og unlock fra vores main.cpp fil, og implementerer derefter Scoped Locking klassen. Meningen med denne klasse er at låse den fælles mutex når en tråd tilgår vektor objektet. Altså kaldes Scoped Locking klassens constructor når setAndTest funktionen kaldes. Når vektoren ikke pilles ved mere kaldes Scoped locking klassens destructor og lukker op for mutexen. Derved får vi den samme funktion som at implementere direkte i main filen.

Koden for Scoped Locking klassen: