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)

谢谢

相关推荐
IMPYLH1 小时前
Linux 的 dir 命令
linux·运维·服务器·数据库
fanged1 小时前
操作系统番外1(Linux的测试体系)(TODO)
linux·运维·服务器
123过去3 小时前
pixiewps使用教程
linux·网络·测试工具·算法·哈希算法
H_老邪3 小时前
Linux 与 Docker 常用命令
linux·运维·服务器·docker
yewq-cn4 小时前
linux 内核设备号
linux·运维·服务器
文静小土豆4 小时前
Linux 进程终止指南:理解 kill 与 kill -9 的核心区别与正确用法
linux·运维·服务器
不懒不懒4 小时前
安装python3.9.7和pycharm-community-2022.3.2.exe以及linux
linux·ide·python·pycharm
IMPYLH4 小时前
Linux 的 df 命令
linux·运维·服务器
wefg14 小时前
【Linux】会话、终端、前后台进程
linux·运维·服务器
zhixingheyi_tian5 小时前
Linux/Windows 免密登录
linux·运维·服务器