I'm new to multi-threads programming and I got confused about where to declare mutex. I got the idea of mutex, lock/unlock by googling a lot. But I still don't know where I need to declare the pthread_mutex_t
variable, and what's the difference.
For example here is Case 1:
#include <pthread.h>
pthread_mutex_t count_mutex;
long long count;
void
increment_count()
{
pthread_mutex_lock(&count_mutex);
count = count + 1;
pthread_mutex_unlock(&count_mutex);
}
Here is Case 2:
struct order_que
{
struct order **orders;
int size;
int head;
int tail;
pthread_mutex_t lock;
};
void *ClientThread(void *arg)
{
struct client_arg *ca = (struct client_arg *)arg;
int i;
for(i=0; i < ca->order_count; i++) {
......
queued = 0;
while(queued == 0) {
pthread_mutex_lock(&(ca->order_que->lock));
......
if(next == ca->order_que->tail) {
pthread_mutex_unlock(&(ca->order_que->lock));
continue;
}
......
pthread_mutex_unlock(&(ca->order_que->lock));
......
}
}
return(NULL);
}
Could anyone tell me what's the difference between these two cases and why I need declare the mutex in this way?