一个关于pthread_mutex_trylock问题
环境:ubuntu6.06+gcc4.0.3
关于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是一样的效果呀