【问题标题】:C - Posix - cond_wait/signalC - Posix - cond_wait/signal
【发布时间】:2016-02-10 14:22:12
【问题描述】:

在纯 C 中,pthread_cond_waitpthread_cond_signal / pthread_cond_destroy, pthread_cond_init 是否设置 errno 以防出错?或者他们只是返回一个值!= 0?

【问题讨论】:

  • 是的,我做了,但它没有指定,它只是说它返回一个值!= 然后 0,现在我的问题是,我如何在运行时对其进行错误检查?我应该这样做 if(pthread_cond_wait(&cond,&mutex) != 0) { perror....} 吗?
  • int ret = pthread_cond_signal(...); switch (ret) { case 0: break; case EINVAL: /* handle the error */break; /*other error cases for other functions*/}.
  • 这个if(pthread_cond_wait(&cond,&mutex)) { handle error }; 不也可以吗?如,它是否仍然运行该函数,如果它返回 0,它将继续运行,如果它返回 != 0 它将跳转到 if 语句? @mch
  • 是的,但是在这种情况下,您只知道发生了错误,而不是发生了错误。

标签: c multithreading signals posix init


【解决方案1】:

来自pthreads man

请注意,pthreads 函数不会设置 errno。

并且特定功能的文档说如果失败他们an error number is returned to indicate the error。所以你只需要检查函数返回的值。

【讨论】:

  • 是的,我已经意识到了这一点,我的问题是:if(pthread_cond_wait(&cond,&mutex)) { handle error }; 这会运行等待函数,并且仅在返回 != 0 时处理错误吗? @tsyvarev
  • 谢谢,我的问题是它是否仍会在 if 中运行该函数,或者只是“测试”它。有时我会遇到这种愚蠢的时刻。
  • 哦,是的,if 子句中的代码总是像正常代码一样编译和执行。您可能会将其与 assert() 宏混淆,在没有启用调试的情况下根本不会编译该条件。
【解决方案2】:

pthread_cond_wait(3) 手册页:http://linux.die.net/man/3/pthread_cond_wait

成功完成后,应返回零值;否则,将返回错误号以指示错误。

pthread_cond_signal(3) 手册页:http://linux.die.net/man/3/pthread_cond_signal

如果成功,pthread_cond_broadcast() 和 pthread_cond_signal() 函数将返回零;否则,将返回错误号以指示错误。

pthread_cond_destroy(3) 手册页:http://linux.die.net/man/3/pthread_cond_destroy

如果成功,pthread_cond_destroy() 和 pthread_cond_init() 函数将返回零;否则,将返回错误号以指示错误。

pthread_cond_init(3) 手册页:http://linux.die.net/man/3/pthread_cond_init

如果成功,pthread_cond_destroy() 和 pthread_cond_init() 函数将返回零;否则,将返回错误号以指示错误。

这意味着不是将错误号放在变量 errno 中,而是返回它。您可以使用strerror 函数获取错误字符串。

#include <stdio.h>
#include <pthread.h>

int ret;
if( (ret = pthread_cond_init( {some args} ) ) != 0 )
    fprintf(stderr, "%s\n", strerror(ret));

【讨论】:

  • 既然我不需要检查错误类型,我可以像if(function){handle error}那样做吗?由于函数仍然在 if 中执行?
  • 是的,但是如果您想知道超时是否发生在等待中,您需要检查错误值。 “除了 [ETIMEDOUT] 的情况外,所有这些错误检查都应该像在函数处理开始时立即执行一样,并且在修改由指定的互斥锁的状态之前实际上会导致错误返回mutex 或 cond 指定的条件变量。”
猜你喜欢
  • 2023-03-28
  • 1970-01-01
  • 1970-01-01
  • 2017-04-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-10-02
相关资源
最近更新 更多