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)

谢谢

相关推荐
石像鬼₧魂石21 小时前
如何配置Fail2Ban的Jail?
linux·学习·ubuntu
椰子今天很可爱1 天前
五种I/O模型与多路转接
linux·c语言·c++
Lueeee.1 天前
Linux kernel Makefile 语法
linux
爱吃山竹的大肚肚1 天前
EasyPOI 大数据导出
java·linux·windows
极地星光1 天前
dmesg 工具的核心功能与作用
linux
福尔摩斯张1 天前
C++核心特性精讲:从C语言痛点出发,掌握现代C++编程精髓(超详细)
java·linux·c语言·数据结构·c++·驱动开发·算法
hgz07101 天前
Linux服务器环境部署与JMeter压测准备
linux·服务器·jmeter
ShirleyWang0121 天前
VMware如何导入vmdk文件
linux·数据库
Lueeee.1 天前
内核menuconfig配置实验
linux
遇见火星1 天前
常见Systemctl语句
linux·服务器·网络·systemctl