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?
arg. For example, you may have two different queues that have seperate locking mutexes. Then the second method is more flexible as that same thread function can be used without changing any of its code - just need to invoke it with differentargvalues.pthread_mutex_t lock;was actuallyint i;, andpthread_mutex_lockwas++andpthread_mutex_unlockwas--, or something like that. Do you know the difference now?