老师您好,我这边在运行时发现互斥量相比读写锁要节省时间

来源:7-4 线程同步之读写锁

林小堂

2020-01-30

老师好,我使用的是Mac的环境,代码和您的一样

//读写锁demo
#include <iostream>
#include <unistd.h>
#include <pthread.h>
#include <vector>
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; //定义互斥量
//pthread_rwlock_t rwlock = PTHREAD_RWLOCK_INITIALIZER; //定义读写锁
//临界资源
int num = 0;
void *reader(void*){
    int times = 10000000;
    while (times --){
        pthread_mutex_lock(&mutex);
        //pthread_rwlock_rdlock(&rwlock);     //读锁
        if (times%1000 == 0){
            //std::cout << "num in reader is " << num << std::endl;
            //sleep(1);
            usleep(10);//睡眠10微秒
        }
       //pthread_rwlock_unlock(&rwlock);
        pthread_mutex_unlock(&mutex);
    }

}

void *writer(void*){
    int times = 10000000;
    while (times --){
        pthread_mutex_lock(&mutex);
        //pthread_rwlock_wrlock(&rwlock);     //写锁
        num += 1;
        //pthread_rwlock_unlock(&rwlock);
        pthread_mutex_unlock(&mutex);
    }
}

int main() {
    std::cout << "Start in main functions"<< std::endl;
    pthread_t thread1,thread2,thread3;
    pthread_create(&thread1,NULL,&reader,NULL);
    pthread_create(&thread2,NULL,&reader,NULL);
    pthread_create(&thread3,NULL,&writer,NULL);
    pthread_join(thread1,NULL);
    pthread_join(thread2,NULL);
    pthread_join(thread3,NULL);
    //std::cout << "num = "<< num << std::endl;
    return 0;
}

执行过程中发现使用读写锁的时间为:
图片描述
使用互斥量的时间为:
图片描述
在这个过程中得到的结论和老师的是相反的,没有找到原因,请问老师这是由于环境的不同导致的吗,麻烦老师帮忙分析一下原因,谢谢老师,期待您的回复。

写回答

1回答

咚咚呛

2020-01-31

确实,老师在自己的mac上也做了测试,得到和你一致的结论,查阅了一些资料,这个主要是内核锁相关的实现带来的差异。

0
2
咚咚呛
回复
林小堂
你可以在Linux机器再做一些实验,估计会得到和老师一样的结论。
2020-01-31
共2条回复

(新版)计算机基础,计算机组成原理+操作系统+网络

编程之前先学这门课,系统补足计算机基础知识,夯实编程地基

7739 学习 · 1580 问题

查看课程