线程相关函数(4)-pthread_mutex_lock(), pthread_mutex_unlock() 互斥锁
互斥锁实例:
#include <pthread.h>
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
int pthread_mutex_destroy(pthread_mutex_t *mutex);
int pthread_mutex_init(pthread_mutex_t *restrict mutex, const pthread_mutexattr_t *restrict attr);
int pthread_mutex_lock(pthread_mutex_t *mutex);
int pthread_mutex_trylock(pthread_mutex_t *mutex);
int pthread_mutex_unlock(pthread_mutex_t *mutex);
示例代码:
#include <pthread.h> #include <stdio.h> #define NLOOP 5000 static pthread_mutex_t counter_mutex = PTHREAD_MUTEX_INITIALIZER; static int counter; void *doit(void *); int main() { pthread_t tidA, tidB; pthread_create(&tidA, NULL, doit, NULL); pthread_create(&tidB, NULL, doit, NULL); /*wait for both threads to terminate*/ pthread_join(tidA, NULL); pthread_join(tidB, NULL); return 0; } void *doit(void *arg) { int i, val; for (i=0; i<NLOOP; i++) { pthread_mutex_lock(&counter_mutex); val = counter; printf("%x: %d\n", (unsigned int)pthread_self(), val+1); counter = val + 1; pthread_mutex_unlock(&counter_mutex); } return NULL; }
运行结果:
....
71025700: 9979
71025700: 9980
71025700: 9981
71025700: 9982
71025700: 9983
71025700: 9984
71025700: 9985
71025700: 9986
71025700: 9987
71025700: 9988
71025700: 9989
71025700: 9990
71025700: 9991
71025700: 9992
71025700: 9993
71025700: 9994
71025700: 9995
71025700: 9996
71025700: 9997
71025700: 9998
71025700: 9999
71025700: 10000