?????????????????????????????????????????????????????????????????????????鶼???????????????????????????????????????????????б??????????????????????????????????????????????????????????????е??????????????????????????????????????????????????????????????????????????P/V???????????????ü???-lpthread??-lrt???

?????????????

????1??????????????

???????????????????????????????PTHREAD_MUTEX_INITIALIZER???????pthread_mutex_init(…?? NULL)???????pthread_mutex_init??

???????????????????????????????(malloc)??????pthread_mutex_init???г??????????????????(free)????????pthread_mutex_destroy.

????int pthread_mutex_init(pthread_mutex_t *restrict mutex?? const pthread_mutexattr_t*restric attr);
????int pthread_mutex_destroy(pthread_mutex_t *mutex);

??????????????????0????????????????

?????????1????????????????????????????????attr???NULL??

????2???????????????????ζ?????????????????????????????????????????????Linux?У???????????????κ?????????LinuxThreads?е?pthread_mutex_destroy()????????????????????????EBUSY???????????????

????2???????????

?????????????????? ???????????м???????????????????????????????????????????????????????????????????????????????????????н?????

????int pthread_mutex_lock(pthread_mutex_t *mutex);  //P???????????????+1??
????int pthread_mutex_trylock(pthread_mutex_t *mutex);
????int pthread_mutex_unlock(pthread_mutex_t *mutex);//V??????????????-1??

??????????????????0???????????????.

?????????1???????????????????????????pthread_mutex_lock?????mutex????????????????????????????????????????

????2??????????trylock?????? ?????????????????????????????????????????????trylock??????????????????? ??????????????????????????????????????trylock?????????????????????????EBUSY?????????????????????

????3????????????????????????phtread_mutex_unlock??

????3????????????????????

????3.1 ??????

???????????????????????????????????????????????е?????????????????????????????????????????????????????????????????????????????Щ??????????????????????????????磬??????????????????????1 ??????? 2???????????????????????????????????????????????????????????????????????

 

??? 1

??? 2

pthread_mutex_lock(&m1);

pthread_mutex_lock(&m2);

do something……

pthread_mutex_unlock(&m2);

pthread_mutex_unlock(&m1);

pthread_mutex_lock(&m2);

pthread_mutex_lock(&m1);

do something……

pthread_mutex_unlock(&m1);

pthread_mutex_unlock(&m2);

????3.2 ?????

 

??? 1

??? 2

pthread_mutex_lock(&m1);

do something……

pthread_mutex_unlock(&m2);

pthread_mutex_lock(&m2);

do something……

pthread_mutex_unlock(&m1);

????3.3 ????

 

??? 1

pthread_mutex_lock(&m1);

do something……//???????Critical Section??

pthread_mutex_unlock(&m1);