MST

星途 面试题库

面试题:C语言中Linux多线程创建基础及数据共享问题

在Linux环境下使用C语言创建多线程,假设有两个线程需要共享一个全局变量count,为了避免竞态条件,应该如何处理?请写出完整的代码示例,包括线程创建、共享变量定义以及处理竞态条件的方法。
40.8万 热度难度
编程语言C

知识考点

AI 面试

面试题答案

一键面试
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>

// 共享变量
int count = 0;
// 互斥锁
pthread_mutex_t mutex;

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

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

int main() {
    pthread_t thread1, thread2;

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

    // 创建线程1
    if (pthread_create(&thread1, NULL, increment_count, NULL) != 0) {
        perror("Failed to create thread 1");
        return 1;
    }
    // 创建线程2
    if (pthread_create(&thread2, NULL, decrement_count, NULL) != 0) {
        perror("Failed to create thread 2");
        return 1;
    }

    // 等待线程1结束
    if (pthread_join(thread1, NULL) != 0) {
        perror("Failed to join thread 1");
        return 1;
    }
    // 等待线程2结束
    if (pthread_join(thread2, NULL) != 0) {
        perror("Failed to join thread 2");
        return 1;
    }

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

    printf("Final count: %d\n", count);

    return 0;
}