MST

星途 面试题库

面试题:C语言实现不同互斥锁粒度场景

假设你正在开发一个多线程的文件处理程序,要求对文件的不同部分进行读写操作。请用C语言代码示例,分别展示粗粒度互斥锁和细粒度互斥锁在该场景下的实现方式,并分析各自的优缺点。
28.6万 热度难度
编程语言C

知识考点

AI 面试

面试题答案

一键面试

粗粒度互斥锁实现

#include <stdio.h>
#include <pthread.h>
#include <stdlib.h>

#define FILE_SIZE 1024
char file_data[FILE_SIZE];
pthread_mutex_t mutex;

void* read_file(void* arg) {
    pthread_mutex_lock(&mutex);
    // 模拟读取文件
    for (int i = 0; i < FILE_SIZE; i++) {
        printf("Reading byte %d: %c\n", i, file_data[i]);
    }
    pthread_mutex_unlock(&mutex);
    return NULL;
}

void* write_file(void* arg) {
    pthread_mutex_lock(&mutex);
    // 模拟写入文件
    for (int i = 0; i < FILE_SIZE; i++) {
        file_data[i] = 'a' + i % 26;
    }
    pthread_mutex_unlock(&mutex);
    return NULL;
}

int main() {
    pthread_t read_thread, write_thread;
    pthread_mutex_init(&mutex, NULL);

    pthread_create(&read_thread, NULL, read_file, NULL);
    pthread_create(&write_thread, NULL, write_file, NULL);

    pthread_join(read_thread, NULL);
    pthread_join(write_thread, NULL);

    pthread_mutex_destroy(&mutex);
    return 0;
}

粗粒度互斥锁优缺点

  • 优点:实现简单,只需要一个互斥锁就能保护整个文件操作,易于理解和维护。
  • 缺点:效率低,因为同一时间只有一个线程能访问文件,即使不同线程访问的是文件的不同部分,也会造成不必要的等待,不利于充分利用多核资源。

细粒度互斥锁实现

#include <stdio.h>
#include <pthread.h>
#include <stdlib.h>

#define FILE_SIZE 1024
#define NUM_SECTIONS 4
#define SECTION_SIZE (FILE_SIZE / NUM_SECTIONS)
char file_data[FILE_SIZE];
pthread_mutex_t mutexes[NUM_SECTIONS];

void* read_file(void* arg) {
    int section = *((int*)arg);
    pthread_mutex_lock(&mutexes[section]);
    // 模拟读取文件特定部分
    for (int i = section * SECTION_SIZE; i < (section + 1) * SECTION_SIZE; i++) {
        printf("Reading byte %d: %c\n", i, file_data[i]);
    }
    pthread_mutex_unlock(&mutexes[section]);
    return NULL;
}

void* write_file(void* arg) {
    int section = *((int*)arg);
    pthread_mutex_lock(&mutexes[section]);
    // 模拟写入文件特定部分
    for (int i = section * SECTION_SIZE; i < (section + 1) * SECTION_SIZE; i++) {
        file_data[i] = 'a' + i % 26;
    }
    pthread_mutex_unlock(&mutexes[section]);
    return NULL;
}

int main() {
    pthread_t read_threads[NUM_SECTIONS], write_threads[NUM_SECTIONS];
    int sections[NUM_SECTIONS];
    for (int i = 0; i < NUM_SECTIONS; i++) {
        pthread_mutex_init(&mutexes[i], NULL);
        sections[i] = i;
    }

    for (int i = 0; i < NUM_SECTIONS; i++) {
        pthread_create(&read_threads[i], NULL, read_file, &sections[i]);
        pthread_create(&write_threads[i], NULL, write_file, &sections[i]);
    }

    for (int i = 0; i < NUM_SECTIONS; i++) {
        pthread_join(read_threads[i], NULL);
        pthread_join(write_threads[i], NULL);
    }

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

细粒度互斥锁优缺点

  • 优点:效率高,不同线程可以同时访问文件的不同部分,提高了并行性,能更好地利用多核资源。
  • 缺点:实现复杂,需要管理多个互斥锁,增加了代码的维护难度,并且可能会出现死锁等问题,需要更小心地设计和编程。