一个关于pthread_mutex_trylock问题 | 以下程序不能锁住变量,请大家看一下是那里写错了。 #include <pthread.h> #include <stdio.h> int ggg; pthread_mutex_t mut1; //= PTHREAD_MUTEX_INITIALIZER; pthread_mutex_t mut2; void *fun1(void *str) { unsigned int s; s = pthread_self(); int p; while(1) { if (!pthread_mutex_trylock(&mut1)) { //sleep(1); if (!pthread_mutex_trylock(&mut2)) {ggg = s % 1000; printf("fun111 %d pth :: %u --> ggg is %d\n", (int)str, s, ggg); sleep(1); printf("fun111 %d pth :: %u **> ggg is %d\n", (int)str, s, ggg); pthread_mutex_unlock(&mut1); pthread_mutex_unlock(&mut2); return 0; }else { //printf("fun111 mut2 %d pth :: %u\n", (int)str, s); pthread_mutex_unlock(&mut2); usleep(1000); } }else {//printf("fun111 mut1 %d pth :: %u\n", (int)str, s); pthread_mutex_unlock(&mut1); usleep(1000); } } }
void *fun2(void *str) { unsigned int s; s = pthread_self(); int p; while(1) { if (!pthread_mutex_trylock(&mut2)) { //sleep(2); if (!pthread_mutex_trylock(&mut1)) {ggg = s % 1000; printf("fun222 %d pth :: %u --> ggg is %d\n", (int)str, s, ggg); sleep(1); printf("fun222 %d pth :: %u **> ggg is %d\n", (int)str, s, ggg); pthread_mutex_unlock(&mut2); pthread_mutex_unlock(&mut1); return 0; }else {//printf("fun222 mut1 %d pth :: %u\n", (int)str, s); pthread_mutex_unlock(&mut1); usleep(1000); } }else {//printf("fun222 mut2 %d pth :: %u\n", (int)str, s); pthread_mutex_unlock(&mut2); usleep(1000); } } }
int main() { int i; pthread_t pthid[100]; pthread_attr_t attr; pthread_attr_init(&attr); pthread_mutex_init(&mut2, NULL); pthread_mutex_init(&mut1, NULL); pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED); for (i = 0; i < 3; ++i) { pthread_create(&pthid[i], &attr, fun1, (void*)i); pthread_create(&pthid[i+20], &attr, fun2, (void*)(i+20)); //pthread_join(pthid[i], NULL); } sleep(100); } ---------------------- 结果: fun111 0 pth :: 3084729264 --> ggg is 264 fun222 21 pth :: 3059551152 --> ggg is 152 fun222 20 pth :: 3076336560 --> ggg is 560 fun222 22 pth :: 3042765744 --> ggg is 744 fun111 2 pth :: 3051158448 --> ggg is 448 fun111 1 pth :: 3067943856 --> ggg is 856 fun111 0 pth :: 3084729264 **> ggg is 856//以下这些都不对了 fun222 21 pth :: 3059551152 **> ggg is 856 fun222 20 pth :: 3076336560 **> ggg is 856 fun222 22 pth :: 3042765744 **> ggg is 856 fun111 2 pth :: 3051158448 **> ggg is 856 fun111 1 pth :: 3067943856 **> ggg is 856//这个除外 --------------------- 为什么这样,它根本就没有锁住变量,照理说它应该和pthread_mutex_lock是一样的效果呀 |
回复内容 | 非阻塞的锁定互斥锁pthread_mutex_trylock #include <pthread.h> int pthread_mutex_trylock( pthread_mutex_t *mutex ); 返回值:函数成功返回0。任何其他返回值都表示错误。
函数是pthread_mutex_lock函数的非阻塞版本。如果mutex参数所指定的互斥锁已经被锁定 的话,调用pthread_mutex_trylock函数不会阻塞当前线程,而是立即返回一个值来描述互 斥锁的状况。 else {//printf("fun111 mut1 %d pth :: %u\n", (int)str, s); pthread_mutex_unlock(&mut1); usleep(1000); }
--------------- 没锁上为什么要解锁呢? |
|
|
转载于:https://blog.51cto.com/xmulqy/120193