MST

星途 面试题库

面试题:C语言互斥锁在复杂数据结构中的应用

假设你有一个用C语言实现的链表数据结构,在多线程环境下可能会被多个线程同时访问和修改。请描述如何使用互斥锁来保证链表操作(插入、删除、遍历)的线程安全性,并编写代码实现链表插入操作的线程安全版本。
47.9万 热度难度
编程语言C

知识考点

AI 面试

面试题答案

一键面试
  1. 使用互斥锁保证链表操作线程安全性的描述
    • 定义一个互斥锁变量,在对链表进行插入、删除、遍历等操作前,先获取互斥锁,这样其他线程在该线程持有锁期间无法进行同样的操作,从而避免数据竞争。
    • 操作完成后,释放互斥锁,允许其他线程获取锁并进行链表操作。
  2. 链表插入操作线程安全版本的代码实现
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>

// 定义链表节点结构
typedef struct Node {
    int data;
    struct Node* next;
} Node;

// 定义链表结构
typedef struct List {
    Node* head;
    pthread_mutex_t mutex;
} List;

// 创建新节点
Node* createNode(int data) {
    Node* newNode = (Node*)malloc(sizeof(Node));
    newNode->data = data;
    newNode->next = NULL;
    return newNode;
}

// 初始化链表
List* createList() {
    List* list = (List*)malloc(sizeof(List));
    list->head = NULL;
    pthread_mutex_init(&list->mutex, NULL);
    return list;
}

// 线程安全的插入操作
void insert(List* list, int data) {
    pthread_mutex_lock(&list->mutex);
    Node* newNode = createNode(data);
    if (list->head == NULL) {
        list->head = newNode;
    } else {
        Node* current = list->head;
        while (current->next != NULL) {
            current = current->next;
        }
        current->next = newNode;
    }
    pthread_mutex_unlock(&list->mutex);
}

// 打印链表
void printList(List* list) {
    pthread_mutex_lock(&list->mutex);
    Node* current = list->head;
    while (current != NULL) {
        printf("%d -> ", current->data);
        current = current->next;
    }
    printf("NULL\n");
    pthread_mutex_unlock(&list->mutex);
}

// 线程函数
void* threadFunction(void* arg) {
    List* list = (List*)arg;
    for (int i = 0; i < 5; i++) {
        insert(list, i);
    }
    return NULL;
}

int main() {
    List* list = createList();
    pthread_t threads[2];

    // 创建两个线程
    for (int i = 0; i < 2; i++) {
        pthread_create(&threads[i], NULL, threadFunction, list);
    }

    // 等待线程结束
    for (int i = 0; i < 2; i++) {
        pthread_join(threads[i], NULL);
    }

    printList(list);

    // 清理
    pthread_mutex_destroy(&list->mutex);
    free(list);

    return 0;
}