## Thursday, February 07, 2008

### mutex in multithread

Mutexes have the property that they can only be locked by one thread at a time. If two threads attempt to lock the same mutex, only one of them succeeds. The other one blocks until the first thread releases the mutex. In general, you use mutexes to protect some piece of shared data. In order to be useful, the mutex itself must be global so that all threads can see it.

int i;                  /* i is shared */pthread_mutex_t ilock;  /* controls access to i */      ...void func(arg1,arg2)  int arg1;      /* arg1 is private */  float *arg2;   /* arg2 is private, *arg2 is shared */{  int zzz;       /*zzz is private(auto storage class)*/  static float f;/*f is shared (static storage class)*/  pthread_mutex_lock(&ilock);  /* lock i */  something = i++;             /* access i */  pthread_mutex_unlock(&ilock);/* unlock i */}

The details can be found at following link