读书人

互斥锁解决方案

发布时间: 2012-05-24 11:55:41 作者: rapoo

互斥锁
为什么这个代码执行的使只输入了一部分,后面的执行就很卡
为啥啊
代码如下:

C/C++ code
#include<pthread.h>#include<stdio.h>#include<errno.h>int i=0; pthread_mutex_t mutex=PTHREAD_MUTEX_INITIALIZER;void thread1(){    printf("come in thread1\n");    int ret;    while(1)    {        ret=pthread_mutex_trylock(&mutex);        if(ret!=EBUSY)        {            pthread_mutex_lock(&mutex);            printf("this is thread1:%d\n",i);            i++;            pthread_mutex_unlock(&mutex);                    }        sleep(1);    }}void thread2(){    printf("come in thread2\n");    int ret;    while(1)    {        ret=pthread_mutex_trylock(&mutex);        if(ret!=EBUSY)        {            pthread_mutex_lock(&mutex);            printf("this is thread2:%d\n",i);            i++;            pthread_mutex_unlock(&mutex);        }        sleep(1);    }}int main(){    pthread_t t1,t2;    printf("main start\n");    pthread_mutex_init(&mutex,NULL);    printf("this is in main and after mutex init\n");    pthread_create(&t1,NULL,(void *)thread1,NULL);    printf("this is in main and at middle of create thread1 and thread2\n");    pthread_create(&t2,NULL,(void *)thread2,NULL);    printf("this is in main and after create thred1 and thread2\n");    pthread_join(t1,NULL);    printf("this is in main and  after thread1 join\n");    pthread_join(t2,NULL);    printf("this is after thread2 join\n");    pthread_mutex_destroy(&mutex);    return 0;}


执行后输出:
main start
this is in main and after mutex init
this is in main and at middle of create thread1 and thread2
this is in main and after create thred1 and thread2
come in thread2
come in thread1

然后就一直卡死在里面

[解决办法]
主循环destroy(mutex)要加while(1)把
不然你mutex都destroy了,还怎么用啊
[解决办法]
1楼正解
[解决办法]
楼主的目的是在主线程中创建出两个线程,两个线程通过一个死循环交替的打印全局变量i的值,然后主调线程阻塞。
这样写是达不到你的目的的,分析如下:
void thread1()
{
printf("come in thread1\n");
int ret;
while(1)
{
ret=pthread_mutex_trylock(&mutex); //尝试给互斥变量加锁,问题:如果这里加锁成功返回0

if(ret!=EBUSY)
{
pthread_mutex_lock(&mutex); //会执行到这里,也就是说再次加锁,这样也就产生了死锁(对一把锁加锁两次)

printf("this is thread1:%d\n",i);
i++;
pthread_mutex_unlock(&mutex); //就算你的互斥两属性是PTHREAD_MUTEX_RECURSIVE,那么你加锁两次释放锁也应该需要两次,锁才会是解锁状态,否则其他的线程是无法对该互斥变量加锁的

}
sleep(1);
}
}


[解决办法]
pthread_mutex_trylock返回0的话表示已经锁住了。。

你pthread_mutex_lock再锁肯定就没法再获得锁了。
这种情况改成这样就行了:
pthread_mutex_lock(&mutex);
printf("this is thread1:%d\n",i);
i++;
pthread_mutex_unlock(&mutex);

读书人网 >C++

热点推荐