Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

errno in Multithread implementation

Tags:

c++

c

errno

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?

like image 330
WildThing Avatar asked Sep 01 '25 21:09

WildThing


2 Answers

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");
}
like image 134
ForEveR Avatar answered Sep 03 '25 09:09

ForEveR


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.

like image 34
Simon Richter Avatar answered Sep 03 '25 11:09

Simon Richter