C/C++ 使用信号量控制线程运行顺序

本文深入解析信号量机制在多线程环境中的应用,包括sem_init()、sem_wait()和sem_post()函数的功能与参数,通过具体代码示例展示信号量如何协调线程间资源竞争,确保线程安全。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#include <stdio.h>
#include <semaphore.h>  // semaphore/seməfɔːr/
#include <pthread.h>


//信号量的主要函数有:


/*
 * 函数名:sem_init()
 * 功能:对指定信号初始化
 * 参数1:*sem:信号,
 * 参数2:pshared=0时,信号在当前进程的多个线程之间共享
 * 参数3:unsigned
 * 参数4:value表示初始化信号的值
 * int sem_init(sem_t *sem,int pshared,unsigned int value);
 */


/*
 * 函数名:sem_wait()
 * 功能:阻塞当前进程,直到信号量的值大于0,解除阻塞,
 *      解除阻塞后sem的值-1表示公共资源执行减少了,例
 *      如:如果你对一个值为2的信号量调用sem_wait(),
 *      线程将会继续执行,信号量的值将-1。当初始化
 *      value=0后,使用sem_wai会阻塞这个线程,这个
 *      线程函数就会等待其它线程函数调用sem_post增加
 *      了了这个值使它不再是0,才开始执行,然后value值-1。
 * 参数:*sem
 * int sem_wait(sem_t *sem);
 */


/*
 * 函数名:sem_post(sem_t *sem);
 * 功能:增加信号量的值+1,当有线程阻塞在这个信号量上时,
 *      调用这个函数会使其中的一个线程不再阻塞,选择机制
 *      由线程的调度策略决定
 * 参数:*sem
 * int sem_post(sem_t *sem);
 */
sem_t sem,sem1,sem2;


void* thread_a(void* arg){
    LOOP:
    sem_wait(&sem2);
    printf("thread_a running \n");
    sem_post(&sem);
    sleep(1);
    goto LOOP;
}


void* thread_b(void* arg){
    LOOP:
    sem_wait(&sem);
    printf("thread_b running \n");
    sem_post(&sem1);
    sleep(1);
    goto LOOP;
}


void* thread_c(void* arg){
    LOOP:
    sem_wait(&sem1);
    printf("thread_c running \n");
    sem_post(&sem2);
    sleep(1);
    goto LOOP;
}


int main(void){
    sem_init(&sem,0,1);
    sem_init(&sem1,0,0);
    sem_init(&sem2,0,0);


    pthread_t id[2];


    pthread_create(&id[0],NULL,thread_a,NULL);
    pthread_create(&id[1],NULL,thread_b,NULL);
    pthread_create(&id[2],NULL,thread_c,NULL);


    pthread_join(id[0],NULL);
    pthread_join(id[1],NULL);
    pthread_join(id[2],NULL);


    return 0;
}
iotek@iotekclass:~/pwz1903C++/Depa/面试题/方凌计算机$ gcc test4.c -pthread
iotek@iotekclass:~/pwz1903C++/Depa/面试题/方凌计算机$ ./a.out
thread_b running 
thread_c running 
thread_a running 
thread_b running 
thread_c running 
thread_a running 
thread_b running 
thread_c running 
thread_a running 
thread_b running 
thread_c running 
thread_a running 
thread_b running 
thread_c running 
thread_a running 
thread_b running 

解释来自https://blog.youkuaiyun.com/u011124985/article/details/79994293

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值