MST

星途 面试题库

面试题:C语言中Linux信号量PV操作的基本实现

在Linux环境下,使用C语言编写一段简单代码,实现基于信号量的PV操作,用于控制两个线程对共享资源的访问,要求清晰体现PV操作的逻辑,并简要解释代码中各部分的作用。
35.2万 热度难度
编程语言C

知识考点

AI 面试

面试题答案

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

// 定义信号量
sem_t semaphore;

// 共享资源
int sharedResource = 0;

// P操作
void P(sem_t *sem) {
    sem_wait(sem);
}

// V操作
void V(sem_t *sem) {
    sem_post(sem);
}

// 线程1函数
void* thread1(void* arg) {
    for (int i = 0; i < 5; i++) {
        P(&semaphore);
        sharedResource++;
        printf("Thread 1: sharedResource = %d\n", sharedResource);
        V(&semaphore);
    }
    return NULL;
}

// 线程2函数
void* thread2(void* arg) {
    for (int i = 0; i < 5; i++) {
        P(&semaphore);
        sharedResource--;
        printf("Thread 2: sharedResource = %d\n", sharedResource);
        V(&semaphore);
    }
    return NULL;
}

int main() {
    // 初始化信号量为1
    sem_init(&semaphore, 0, 1);

    pthread_t tid1, tid2;

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

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

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

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

    // 销毁信号量
    sem_destroy(&semaphore);

    return 0;
}

代码各部分作用解释:

  1. 信号量定义和共享资源
    • sem_t semaphore; 定义一个信号量变量。
    • int sharedResource = 0; 定义一个共享资源,初始值为0。
  2. P操作
    • void P(sem_t *sem) { sem_wait(sem); } 实现P操作,sem_wait函数会将信号量的值减1,如果信号量的值为0,则线程会阻塞,直到信号量的值大于0。
  3. V操作
    • void V(sem_t *sem) { sem_post(sem); } 实现V操作,sem_post函数会将信号量的值加1,唤醒可能被阻塞的线程。
  4. 线程函数
    • thread1thread2函数分别对共享资源进行加1和减1操作。在操作前调用P操作获取信号量,操作后调用V操作释放信号量,以此控制对共享资源的访问。
  5. 主函数
    • sem_init(&semaphore, 0, 1); 初始化信号量,值为1,表示共享资源初始可用。
    • pthread_create 创建两个线程。
    • pthread_join 等待两个线程执行完毕。
    • sem_destroy(&semaphore); 销毁信号量,释放资源。