MST

星途 面试题库

面试题:C语言多线程环境下的资源共享问题

在C语言多线程编程中,假设有多个线程需要访问和修改同一个全局变量,为了避免数据竞争,应该采取什么措施?请用代码示例说明如何使用互斥锁(mutex)来解决这个问题。
23.6万 热度难度
编程语言C

知识考点

AI 面试

面试题答案

一键面试
  1. 措施
    • 在C语言多线程编程中,当多个线程需要访问和修改同一个全局变量时,为避免数据竞争,可以使用互斥锁(mutex)、信号量、读写锁等同步机制。其中互斥锁是一种常用的简单方法,它通过锁定和解锁机制来保证同一时间只有一个线程能访问共享资源(这里的全局变量)。
  2. 代码示例
#include <stdio.h>
#include <pthread.h>

// 定义全局变量
int global_variable = 0;
// 定义互斥锁
pthread_mutex_t mutex;

// 线程函数
void* increment(void* arg) {
    // 加锁
    pthread_mutex_lock(&mutex);
    for (int i = 0; i < 1000000; i++) {
        global_variable++;
    }
    // 解锁
    pthread_mutex_unlock(&mutex);
    return NULL;
}

int main() {
    // 初始化互斥锁
    pthread_mutex_init(&mutex, NULL);

    pthread_t thread1, thread2;

    // 创建线程1
    if (pthread_create(&thread1, NULL, increment, NULL) != 0) {
        printf("\n ERROR creating thread1");
        return 1;
    }
    // 创建线程2
    if (pthread_create(&thread2, NULL, increment, NULL) != 0) {
        printf("\n ERROR creating thread2");
        return 2;
    }

    // 等待线程1结束
    if (pthread_join(thread1, NULL) != 0) {
        printf("\n ERROR joining thread");
        return 3;
    }
    // 等待线程2结束
    if (pthread_join(thread2, NULL) != 0) {
        printf("\n ERROR joining thread");
        return 4;
    }

    // 销毁互斥锁
    pthread_mutex_destroy(&mutex);

    printf("Final value of global_variable: %d\n", global_variable);
    return 0;
}

在上述代码中:

  • 首先定义了一个全局变量global_variable和一个互斥锁mutex
  • increment线程函数中,通过pthread_mutex_lock对互斥锁加锁,这样在同一时间只有一个线程能进入for循环修改global_variable,操作完成后通过pthread_mutex_unlock解锁。
  • main函数中,初始化互斥锁,创建两个线程去调用increment函数,等待两个线程执行完毕后,销毁互斥锁并输出global_variable的最终值。这样通过互斥锁就有效地避免了多线程访问全局变量时的数据竞争问题。