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)

谢谢

相关推荐
面向对象World7 小时前
Z8350 Broadcom SDIO网卡调试Ubuntu 22.04 Server版
linux·运维·ubuntu
Irissgwe7 小时前
12、多路转接 select
linux·io多路转接·select
无足鸟ICT7 小时前
【RHCA+】编辑多个文件
linux
fengyehongWorld8 小时前
Linux fd命令
linux
AIMath~8 小时前
hermes agent安装在Linux centos中
linux·运维·服务器
赵民勇8 小时前
如何查看一个二进制程序是否设置了rpath或runpath?
linux·c++
小王师傅668 小时前
深入解析:Docker在Mac上的运行本质与Linux进程管理机制
linux·macos·docker
Irissgwe8 小时前
9、数据链路层
linux·网络·mac·ip·数据链路层·arp协议·以太网帧格式
lwprain8 小时前
Umi-ocr2.1.5的linux部署,仅做记录
linux·服务器·umi-ocr
鹏大师运维8 小时前
统信UOS安装Subtitle Edit并使用Edge-TTS生成AI语音教程
linux·前端·人工智能·edge·麒麟·统信uos·ai语音