c++ - 多线程实现中的errno

标签 c++ c errno

要在多线程应用程序中使用 errno,请引用 http://www.cplusplus.com/reference/cerrno/errno/表示它应该在每个线程中本地实现。这是什么意思?

最佳答案

errno 应该是thread-local。在每个thread中这个变量的值可以不同。

that it should be locally implemented in every thread

errno 实现为thread_local 变量不是您的责任。它适用于编译器开发人员。

来自 cppreference.com

errno is a preprocessor macro used for error indication. It expands to a thread-local modifiable lvalue of type int. (since C++11)

只是在 C++11 编译器中,这段代码永远不应该断言

#include <iostream>
#include <cerrno>
#include <thread>
#include <cassert>

int g_errno = 0;

void thread_function()
{
   errno = E2BIG;
   g_errno = errno;
}

int main()
{
   errno = EINVAL;
   std::thread thread(thread_function);
   thread.join();
   assert(errno != g_errno && "not multithreaded");
}

关于c++ - 多线程实现中的errno,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17612112/

相关文章:

c++ - boost 功能并绑定(bind)外部符号

c++ - 在 int 变量中查找 '1' 的奇偶校验

c - 多线程计算矩阵乘积的时间成本

与 C 中的 Union 混淆

c - 需要帮助在 {c} 中制作素数行

c++ - _mkdir给出错误的错误窗口

c++ - 由于构造函数无法推回类对象

c++ - 如何使用指针合并 2 个数组?

python - 为什么 os.rename() 在 Python 2.7 中引发异常?

c - 为什么 errno,当 POSIX 函数通过返回 -1 或 NULL 指示错误条件时