关于pthread_mutex_lock和trylock的区别

pthread_mutex_lock会阻塞,pthread_mutex_trylock是非阻塞的。
举例:lock
当A线程去lock一个锁时,如果该锁已被其他线程锁住,则A线程会被挂起,等待该锁被释放后,再进行lock。

图中如果线程1在获取lock1时,发现该锁已被占用,则线程1会被挂起,不再执行后面的程序直到抢占到lock1。在这里插入图片描述

举例:trylock
当线程A去trylock一个锁时,如果该锁被占用,则线程A继续执行下面的程序,不会被挂起。

图中线程1去trylock一下lock1时,如果锁被占用,则继续执行下面的程序
在这里插入图片描述

总结:人如其名,trylock就是尝试锁一下,锁不到就拉倒,不会影响自己进行下一步操作。lock就比较犟,锁不到的话,我就等着,等到我能锁了,再进行一下步操作。(如果哪里说的不对或者不准确,请多指教,感谢)

下面是我用的测试代码段,大家可以在此基础上自行更改测试。

#include<pthread.h>
#include<stdio.h>
#include<time.h>
pthread_mutex_t lock1=PTHREAD_MUTEX_INITIALIZER;
int count=0;
void* thread_1(void *arg)
{
    int i=0;
    int tmp=0;
    pthread_mutex_lock(&lock1); 
    while (i<5000000)
    {            
        tmp=count;
        i++;
        count=tmp+1;
        //printf("main pthread_self = %u,i=%d\n", (unsigned int)pthread_self(),i);      
    }
    printf("pthread_self = %d,count=%d\n",1,count);
    pthread_mutex_unlock(&lock1);
    
    return 0;
}

void* thread_2(void *arg)
{
    int i=0;
    int tmp=0;
    pthread_mutex_lock(&lock1); 
    while (i<50)
    {          
        printf("thread2\n");  
        tmp=count;
        i++;
        count=tmp+1;      
        //printf("main pthread_self = %u,i=%d\n", (unsigned int)pthread_self(),i);      
    }
    printf("pthread_self = %d,count=%d\n",2,count);
    pthread_mutex_unlock(&lock1);
    
    return 0;
}

int main()
{   
    float time_s,time_ns,time_ms;
    struct timespec ts1,ts2;
    pthread_t th1,th2;
    clock_gettime(CLOCK_MONOTONIC,&ts1);//记录函数开始时间
    pthread_create(&th1,NULL,thread_1,NULL);
    pthread_create(&th2,NULL,thread_2,NULL);

    pthread_join(th1,NULL);
    pthread_join(th2,NULL);

    printf("count=%d\n",count);
    clock_gettime(CLOCK_MONOTONIC,&ts2);//记录函数结束时间
        time_s = ts2.tv_sec - ts1.tv_sec;  //得到秒的时间
    time_ns = (ts2.tv_nsec - ts1.tv_nsec); //得到纳秒的时间
    //由于总的时间=time_s+time_ns
    //为了显示方便,将总的时间统一转化为毫秒
    time_ms = time_s*1000+time_ns/1000000;
    printf("run time is %fms",time_ms);
    return 0;
}
  • 9
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

zxx147

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值