首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 操作系统 > UNIXLINUX >

linux 多线程锁的有关问题 trylock得不到锁

2013-03-22 
linux 多线程锁的问题 trylock得不到锁如题:测试代码如下,为何线程一中while的最后不sleep 1s,那么线程2tr

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");
        printf("thread1--->\n");


        printf("thread1--->\n");
        printf("thread1--->\n");
        sleep(1);   /*只有开启睡眠才可以让trylock获得锁*/
这几句都去掉也没问题!
./a.out 
[解决办法]
 head -20
test
condition variable study!
start thread2....
thread1--->1
thread2-->0
thread2-->-1
thread2-->-2
thread2-->-3
thread2-->-4
thread2-->-5
thread2-->-6
thread2-->-7
thread2-->-8
thread2-->-9
thread2-->-10
thread2-->-11
thread2-->-12
thread2-->-13
thread2-->-14
thread2-->-15


当然可能会出现线程1在一个时间片内刚好循环一遍,,那当线程2获得时间片时,线程2就每次都获得不到锁了. 这种情况应该只会发生在单核cpu上吧.
我的是双核的cpu.

热点排行