Thread mutex behaviour
- by Alberteddu
Hi there,
I'm learning C. I'm writing an application with multiple threads; I know that when a variable is shared between two or more threads, it is better to lock/unlock using a mutex to avoid deadlock and inconsistency of variables. This is very clear when I want to change or view one variable.
int i = 0; /** Global */
static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
/** Thread 1. */
pthread_mutex_lock(&mutex);
i++;
pthread_mutex_unlock(&mutex);
/** Thread 2. */
pthread_mutex_lock(&mutex);
i++;
pthread_mutex_unlock(&mutex);
This is correct, I think. The variable i, at the end of the executions, contains the integer 2.
Anyway, there are some situations in which I don't know exactly where to put the two function calls.
For example, suppose you have a function obtain(), which returns a global variable. I need to call that function from within the two threads. I have also two other threads that call the function set(), defined with a few arguments; this function will set the same global variable. The two functions are necessary when you need to do something before getting/setting the var.
/** (0) */
/** Thread 1, or 2, or 3... */
if(obtain() == something) {
if(obtain() == somethingElse) {
// Do this, sometimes obtain() and sometimes set(random number) (1)
} else {
// Do that, just obtain(). (2)
}
} else {
// Do this and do that (3)
// If # of thread * 3 > 10, then set(3*10) For example. (4)
}
/** (5) */
Where I have to lock, and where I have to unlock?
The situation can be, I think, even more complex. I will appreciate an exhaustive answer.
Thank you in advance.
—Alberto