linux 函数 sem_init () 信号量、sem_destroy()

(1)



(2) 代码举例:

c 复制代码
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <semaphore.h>
#include <unistd.h>

sem_t semaphore;

void* thread_function(void* arg) 
{
    sem_wait(&semaphore); // 等待信号量
    printf("Thread %ld entered critical section.\n", (long)arg);
    sleep(1);             // 模拟临界区工作
    printf("Thread %ld leaving critical section.\n", (long)arg);
    sem_post(&semaphore); // 释放信号量
    return NULL;
}

int main() 
{
    pthread_t thread1, thread2;

    if (sem_init(&semaphore, 0, 1) != 0) {  // 初始化二进制信号量,初始值为1
        perror("sem_init");
        exit(EXIT_FAILURE);
    }

    pthread_create(&thread1, NULL, thread_function, (void*)1);   // 创建两个线程
    pthread_create(&thread2, NULL, thread_function, (void*)2);

    pthread_join(thread1, NULL);    pthread_join(thread2, NULL); // 等待线程完成
    
    sem_destroy(&semaphore);  // 销毁信号量

    return 0;
}

++ 在这个示例中,两个线程尝试进入临界区,但由于信号量的初始值为 1,因此一次只能有一个线程进入。当一个线程进入临界区后,它会等待一秒钟(模拟工作),然后离开临界区并释放信号量,允许另一个线程进入。

(3)

(4)

谢谢

相关推荐
誰能久伴不乏22 分钟前
Linux系统调用概述与实现:深入浅出的解析
linux·运维·服务器
程序员学习随笔34 分钟前
Linux进程深度解析(2):fork/exec写时拷贝性能优化与exit资源回收机制(进程创建和销毁)
linux·运维·服务器
mmoyula34 分钟前
【RK3568 PWM 子系统(SG90)驱动开发详解】
android·linux·驱动开发
-SGlow-1 小时前
MySQL相关概念和易错知识点(2)(表结构的操作、数据类型、约束)
linux·运维·服务器·数据库·mysql
代码改变世界ctw2 小时前
Linux内核设计与实现 - 第14章 块I/O层
linux·运维·服务器
van叶~4 小时前
Linux网络-------1.socket编程基础---(TCP-socket)
linux·网络·tcp/ip
风吹落叶花飘荡4 小时前
Ubuntu系统 系统盘和数据盘扩容具体操作
linux·运维·ubuntu
zoulingzhi_yjs4 小时前
haproxy配置详解
linux·云原生
bingbingyihao4 小时前
Node.js 模拟 Linux 环境
linux·node.js
大神的风范4 小时前
从0开始学linux韦东山教程Linux驱动入门实验班(5)
linux