【问题标题】:why doesn't sem_wait block为什么 sem_wait 不阻塞
【发布时间】:2016-12-14 10:41:01
【问题描述】:
static int res1 = 0;
static int res2 = 0;
static int res3 = 0;

static int counter = 0;
static sem_t sem;



void * func_thread1(void *p)
{
    sleep(2);
    res1 = 1;
    printf("func_thread1\n");
    sem_post(&sem);
    return NULL;
}

void * func_thread2(void *p)
{
    sleep(2);
    res2 = 2;
    printf("func_thread2\n");
    sem_post(&sem);
    return NULL;
}

void * func_thread3(void *p)
{
    sem_wait(&sem);
    sem_wait(&sem);
    res3 = res1 + res2;
    printf("func_thread3\n");
    return NULL;
}




void main()
{
    sem_init(&sem, 0, counter);
    pthread_t pd1, pd2, pd3;
    pthread_create(&pd1, NULL, func_thread1, NULL);
    pthread_create(&pd2, NULL, func_thread2, NULL);
    pthread_create(&pd3, NULL, func_thread3, NULL);

    //pthread_join(pd3, NULL);

    printf("main_thread\n");
    printf("%d", res3);
}

我正在尝试了解信号量的工作原理。
我正在尝试让td3 块等待td1td2

在我看来,sem_wait 会阻塞两次。如果func_thread1func_thread2中的sem_posts被执行,func_thread3可以继续。

但是,除非我在 main 中添加 pthread_join(td3, NULL),否则它不起作用。我认为加入是没有必要的,因为sem_wait 可以阻止。

所以pthread_join 是必要的还是我错误地使用了信号量?

【问题讨论】:

    标签: c semaphore


    【解决方案1】:

    pthread_join 在您的实现中是强制性的。

    否则您的进程完成(即 main 返回),并且所有任务(即线程)在线程 3 打印任何内容之前被终止。

    【讨论】:

    • sem_wait() 递减(锁定)sem 指向的信号量。如果信号量的值大于零,则递减继续,函数立即返回。如果信号量当前的值为零,则调用会阻塞,直到可以执行递减(即信号量值高于零)或信号处理程序中断调用。
    • 您会看到,“如果信号量当前的值为零,则调用阻塞...”。这里的block是什么意思?
    • 它会阻塞调用sem_wait的线程的执行,而不是整个进程或其他任务。
    猜你喜欢
    • 2022-01-20
    • 2020-08-10
    • 2016-02-24
    • 1970-01-01
    • 1970-01-01
    • 2012-10-19
    • 1970-01-01
    • 2021-05-19
    • 1970-01-01
    相关资源
    最近更新 更多