互斥锁实例:
#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#include #define NLOOP 5000static 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
运行结果:
....
71025700: 9979
71025700: 998071025700: 998171025700: 998271025700: 998371025700: 998471025700: 998571025700: 998671025700: 998771025700: 998871025700: 998971025700: 999071025700: 999171025700: 999271025700: 999371025700: 999471025700: 999571025700: 999671025700: 999771025700: 999871025700: 999971025700: 10000