日期:2014-05-16  浏览次数:20767 次

linux 多线程锁的问题 trylock得不到锁
如题:
测试代码如下,为何线程一中while的最后不sleep 1s,那么线程2trylock就永远的得不到锁,这个正常吗?


#include <stdio.h>
#include <pthread.h>
 
 
pthread_mutex_t mutex;
pthread_cond_t cond;
int sum = 0;
void *thread1(void *arg)
{
    while(1)
    {
        pthread_mutex_lock(&mutex);
        sum++;
        printf("thread1--->%d\n",sum);
        sleep(3);
        pthread_mutex_unlock(&mutex);
        printf("thread1--->\n");
        printf("thread1--->\n");
        printf("thread1--->\n");
        printf("thread1--->\n");
        printf("thread1--->\n");
        printf("thread1--->\n");
        sleep(1);   /*只有开启睡眠才可以让trylock获得锁*/
    }
}
 
void *thread2(void *arg) 
{
    printf("start thread2....\n");
    while(1)
    {
        int rel = pthread_mutex_trylock(&mutex);
        if(0 == rel)
        {
            sum--;
            printf("thread2-->%d\n",sum);
            pthread_mutex_unlock(&mutex);
        }        
         
    }
}
 
int main() 
{
    printf("test\n");
    sleep(1);
    pthread_t thid1, thid2;    
    printf("condition variable study!\n");
    pthread_mutex_init(&mutex, NULL);
    pthread_cond_init(&cond, NULL);
    pthread_create(&thid1, NULL, (void *) thread1, NULL);
    pthread_create(&thid2, NULL, (void *) thread2, NULL);
     
    pthread_join(thid1,NULL);
    pthread_join(thid2,NULL);
    return 0;
 
}

------解决方案--------------------
没有sleep(1)的话

pthread_mutex_unlock 之后 立即调用 pthread_mutex_lock,
建议thread1里pthread_mutex_unlock之后sched_yield
thread2里pthread_mutex_trylock 改为pthread_mutex_lock
------解决方案--------------------
把        printf("thread1--->\n");
        printf("thread1--->\n");
        printf("thread1--->\n");
  &