sem_wait & sem_post

本文介绍了一个使用sem_wait和sem_post实现线程间同步的例子。通过创建两个线程,其中一个线程等待信号量,另一个线程根据输入发送信号量。文章展示了如何初始化和销毁信号量,以及如何创建和管理线程。

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

sem_wait 和 sem_post这两个函数经常在线程同步时使用,伴随的还有创建和销毁函数sem_init,sem_destroy

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <semaphore.h>
#include <pthread.h>

static sem_t sem_t1;
static int status = 1;
static pthread_t pthread_t1 = -1;
static pthread_t pthread_t2 = -1;

void *f1(void)
{
    while(status)
    {
        sem_wait(&sem_t1);            //阻塞,等待sem_post发信号唤醒
        printf("hello world.\n");
    }
    printf("bye bye.\n");
    pthread_exit(NULL);
}

void *f2(void)
{
    char buf[128] = {0};
    while(1)
    {
        scanf("%s", buf);
        printf("you input is:%s\n", buf);
        if(!strcmp("0", buf))
        {
            status = 0;
            sem_post(&sem_t1);         //唤醒sem_wait,推出程序
            break;
        }
        memset(buf, 0, sizeof(buf));   //唤醒sem_wait
        sem_post(&sem_t1);
    }
    pthread_exit(NULL);
}


void create(void)
{
    int ret = -1;
    ret = sem_init(&sem_t1, 0 , 0);    //初始化信号量
    if(ret)
    {
        printf("sem_init error ret=%d\n", ret);
        return;
    }
    ret = pthread_create(&pthread_t1, NULL, (void*)f1, NULL);
    if(ret)
    {
        printf("pthread_create t1 ret=%d\n", ret);
        return;
    }
    ret = pthread_create(&pthread_t2, NULL, (void*)f2, NULL);
    if(ret)
    {
        printf("pthread_create t2 ret=%d\n", ret);
    }
}

void destroy(void)
{
    printf("waiting thread exit.\n");
    if(pthread_join(pthread_t1, NULL) || pthread_join(pthread_t2, NULL))
    {
        perror("pthread_join");
    }
    sem_destroy(&sem_t1);             //销毁信号量
}

int main(int argc, char const *argv[])
{
    create();
    destroy();
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值