c++ 中的 errno 是线程安全的

创建日期: 2024-11-19 15:06 | 作者: 风波 | 浏览次数: 24 | 分类: C++

来源:https://stackoverflow.com/questions/17612112/errno-in-multithread-implementation

答案1:

errno should be thread-local. In each thread value of this variable can be different.

that it should be locally implemented in every thread

It's not your duty to implement errno as thread_local variable. It's work for compiler developers.

From 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)

Simply in C++11 compilers this code should never assert

#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");
}

答案2

Historically, errno was a common variable of type int -- i.e. every module brought its own definition, and the linker was responsible for merging them. So programs simply stated int errno; globally and had a working definition.

This breaks down in multithreaded environments, because there is only a single variable. Thus, errno.h now needs to define something that is an lvalue int, and programs should not define their own errno.

The GNU C library for example defines something similar to

#define errno (*(__errno_location()))

where __errno_location() is an inline function that calculates the address of the thread-local errno.

All of this is of no concern to the application, except that it is an error to define your own errno.

24 浏览
18 爬虫
0 评论