Reputation: 324
Trying to understand :
C.2.9 Clause 19: diagnostics library [diff.cpp03.diagnostics] 19.4
Change: Thread-local error numbers
Rationale: Support for new thread facilities.
Effect on original feature: Valid but implementation-specific C++ 2003 code that relies on errno being the same across threads may change behavior in this International Standard.
I understand <error.h>
content is in header <cerrno>
but we have to define errno
as a macro. Can anyone explain what we can do so that errno
would act the same way as it was in C++03 during multi-threading?
Upvotes: 1
Views: 319
Reputation: 11317
C++11 us the first official standard that has a notion of multi-threading. This implies that if you use multiple threads in C++03 or C++98 you are using undefined behavior.
The whole idea about this change is about the following code:
functionThatSetsErrNo();
if (errno == something)
...
If you run this code and the execution results in functionThatSetsErrNo of thread 1, followed by functionThatSetsErrNo of thread 2, followed by the if-statements these if-statements do the right thing in C++11 and gave you a race condition in C++03 possibly combined with the errno
of the second execution.
So what did change? If you after calling functionThatSetsErrNo started a thread, that thread no longer can read the errno
value. Or similarly, if you have synchronization between threads and one calls the function and the other reads errno
.
I hope this indicates that this change ain't too much to worry about as this delayed requesting of errno
is something that is barely done and relying on transfer over threads is even done less.
If you do end up with this situation, you need to put a global std::atomic
in your program and after execution assign errno
into it while reading it from another thread. Although, I actually would recommend getting rid of such strange behavior.
Upvotes: 2
Reputation: 546083
You don’t need to change anything.
The change in the standard is purely because C++03 had no notion of threads, and the abstract machine model used by the standard to describe the semantics of standard C++ code needed to be updated for C++11 to support threads.
But the observable behaviour of errno
in conforming C++ code stayed roughly the same, with the sole exception that errno
is now defined thread-locally, and if your code assumes that the value of errno
is the same across threads it will break.
Upvotes: 4