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)

谢谢

相关推荐
Xena_Networks9 分钟前
SierraNet协议分析使用指导[RDMA]| 如何设置 NVMe QP 端口以进行正确解码
linux·服务器·网络
滴水之功1 小时前
Ubuntu22.04怎么退出Emergency Mode(紧急模式)
linux·运维·服务器
小馬佩德罗2 小时前
Linux/AndroidOS中进程间的通信&线程间的同步 - 信号量
linux·信号量
wqqqianqian2 小时前
国产linux系统(银河麒麟,统信uos)使用 PageOffice 在线打开Word文件,并用前端对话框实现填空填表
linux·前端·word·pageoffice
清风来点灯3 小时前
Ubuntu22.04安装显卡驱动/卸载显卡驱动
linux·笔记·ubuntu
吴爃4 小时前
linux搭建hadoop学习
linux·hadoop·学习
海尔辛4 小时前
学习黑客Linux Flags and Switches 入门
linux·运维·学习
檀越剑指大厂4 小时前
【Linux系列】跨平台安装与配置 Vim 文本编辑器
linux·运维·vim
Johny_Zhao5 小时前
思科安全大模型SOC作业应用分析
linux·网络·人工智能·网络安全·ai·信息安全·云计算·shell·devops·cisco·yum源·系统运维·itsm
阿沁QWQ5 小时前
目录粘滞位的使用
linux