pthread_mutex_lock() 是系统调用吗?

问题描述 投票:0回答:1

我正在尝试测量

pthread_mutex_lock()
的系统时间和用户时间,这是我想到的功能:

void measure_mutex_lock_time(double *user_time, double *system_time) {
    pthread_mutex_t mutexes[NUM_ITERATIONS];
    for (int i = 0; i < NUM_ITERATIONS; i++) {
        if (pthread_mutex_init(&mutexes[i], NULL) != 0) {
            perror("pthread_mutex_init failed");
            exit(EXIT_FAILURE);
        }
    }

    struct rusage start, end;
    double total_user_time = 0;
    double total_system_time = 0;

    getrusage(RUSAGE_SELF, &start);
    for (int i = 0; i < NUM_ITERATIONS; ++i) {
        pthread_mutex_lock(&mutexes[i]);
    }
    getrusage(RUSAGE_SELF, &end);

    for (int i = 0; i < NUM_ITERATIONS; ++i) {
        pthread_mutex_unlock(&mutexes[i]);
        pthread_mutex_destroy(&mutexes[i]);
    }

    total_system_time = get_time_diff(start.ru_stime, end.ru_stime);
    total_user_time = get_time_diff(start.ru_utime, end.ru_utime);

    getrusage(RUSAGE_SELF, &start);
    for (int i = 0; i < NUM_ITERATIONS; ++i) {
    }
    getrusage(RUSAGE_SELF, &end);

    double total_user_time2 = get_time_diff(start.ru_utime, end.ru_utime);
    double total_system_time2 = get_time_diff(start.ru_stime, end.ru_stime);

    *user_time = (total_user_time - total_user_time2) / NUM_ITERATIONS;
    *system_time = (total_system_time - total_system_time2) / NUM_ITERATIONS;
}

结果是:

mutex user time: 0.000000e+00
mutex sys time: 1.100000e-08

这对我来说似乎很奇怪,因为我希望 mutex_lock 不应该是系统调用。我希望该操作完全在用户空间中进行。

我的代码有问题还是我只是认为它有问题?

c operating-system mutex
1个回答
0
投票

在现代 Linux 上,互斥体是通过

futex
机制实现的。

基本实现如下所示:

while (!atomic_compare_and_swap(&lock, 0, 1)) {
    futex_wait(&lock, 0);
}

当锁没有竞争时,获取锁完全是用户空间的操作。当锁被争用时,进程将进入睡眠状态,这涉及系统调用。

© www.soinside.com 2019 - 2024. All rights reserved.