Informations

Auteur(s) Cyril Pletinckx
Date limite Pas de date limite
Limite de soumission Pas de limite
Étiquettes de catégories S6, Level 2, Threads

Etiquettes

Se connecter

[S6] Protect the variable

For now, you did exercises that concerned only one thread, i.e. only one unit of computing. Threads are a very powerful tool to compute faster when you have a large amount of calculations to do. In the project, you will work with them and as they are not so easy to use, we propose you doing some exercises to practice with them.


Shared variable

For this first exercise concerning threads, you have to protect one variable from multiple concurrent accesses. You don't have to create the threads, assume they already exist and you must just protect the nb calls to the function "inc()" that calls itself a global variable used by many different threads. For this, use the mutex given as argument (you don't have to initialise it). You can then only use these functions : pthread_mutex_lock(3) and pthread_mutex_unlock(3).

/*
* Function used to protect a global variable used in the function inc().
*
* @inc : the function that must be called in critical (= protected) section
* @nb : the number of times the function inc() has to be called
* @mutex : an initialised mutex that has to be used for the protection
*
* @return 0 if no error, -1 otherwise
*/
int protect(void inc(void), int nb, pthread_mutex_t* mutex){