/*例子:下面第二次加锁时将出现死锁,如果改为PTHREAD_MUTEX_ERRORCHECK_NP类型,第二次加锁将会返回非零值,不会出现死锁。*/ #include <stdlib.h> #include <pthread.h> #include <stdio.h> #include <sched.h> #include <sched.h> void *consumer1(void *p) { printf("<<<(%u),%d\n", (unsigned)pthread_self(),1); } void *consumer2(void *p) { printf("<<<(%u),%d\n", (unsigned)pthread_self(), 2); } int main(int argc, char *argv[]) {pthread_mutex_t mu ; pthread_t t1, t2, t3; int ret; pthread_mutexattr_t mutexattr; pthread_mutexattr_init(&mutexattr); pthread_mutexattr_settype(&mutexattr, PTHREAD_MUTEX_ERRORCHECK_NP); pthread_mutex_init(&mu, &mutexattr); if(!pthread_mutex_lock(&mu)) printf("get mutex (mian)\n"); if(!pthread_mutex_lock(&mu)) printf("get mutex (main)\n"); ret = pthread_create(&t1, NULL, consumer1, NULL); ret = pthread_create(&t2, NULL, consumer2,NULL); if(ret != 0) { printf("create failed,%d\n", ret); exit(1); } sleep(2); printf("main returned\n"); return 0; } /*注意: PTHREAD_MUTEX_TIMED_NP类型的锁,一个线程加的锁可以被另一个线程解锁,也可以解除未被锁定的锁,不会返回错误。 PTHREAD_MUTEX_ERRORCHECK_NP类型的,加锁和解锁要同一个线程,如果某个线程尝试解除锁定的互斥锁不是由该线程锁定或者未锁定,则将返回错误。*/
时间: 2024-12-29 06:49:42