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)

谢谢

相关推荐
繁梦溪3 分钟前
在Ubuntu子系统中基于Nginx部署Typecho
linux·nginx·ubuntu
莫非技术栈3 分钟前
Ubuntu环境通过Ollama部署DeepSeek-R1模型教程
linux·运维·ubuntu·语言模型
努力成为DBA的小王1 小时前
MySQL(导入sql文件)
linux·运维·数据库·sql·mysql
数据的世界012 小时前
解决.NET程序通过网盘传到Linux和macOS不能运行的问题
linux·运维·服务器·macos
千航@abc4 小时前
vim如何设置自动缩进
linux·编辑器·vim
laimaxgg5 小时前
Linux 非阻塞IO
linux·运维·服务器·网络协议
laochen9856 小时前
缓冲区和c库的简单实现
linux
Golinie10 小时前
【C++高并发服务器WebServer】-7:共享内存
linux·服务器·c++·webserver
时差freebright13 小时前
【Linux系统】进程间通信:认识命名管道
linux·服务器·网络