To use errno in multithread application this reference http://www.cplusplus.com/reference/cerrno/errno/ indicates that it should be locally implemented in every thread. What does that mean?
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");
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With