atomic<int> for older c++ compilers - c++

I am using atomic<int> in my code, but the machine in which now I'm compiling has an older g++ version which doesn't support C++11. Is there any equivalent class available on the net, so that I can use it in my code, or if not, where I can find the C++11 implementation of atomic<int> so I can copy it from there. Can this be easily done?

The proposed (i.e. unofficial) Boost.Atomic library aims to do exactly this. I don't know what state it's in currently, but it's used in the implementation of the recently (officially) accepted Boost.Lockfree library, so presumably it's usable.
EDIT — updated links, now that both Atomic and Lockfree have officially been in Boost for some time:
Boost.Atomic
Boost.Lockfree

Hans Boehm's atomic ops library is good, although it's hard to determine what's available on various platforms.
If you're OK with the LGPL, Intel TBB has what you're looking for as well (plus a lot of other stuff).
If you're only looking at GCC, then you may be able to get away with just using GCC's intrinsics (I'm not sure which version of GCC those showed up in, but they've been around for a while).

sig_atomic_t
This is an integral type of an object that can be accessed as an
atomic entity, even in the presence of asynchronous signals.
in gcc is atomic
To avoid uncertainty about interrupting access to a variable, you can use a particular data type for which access is always atomic: sig_atomic_t.

Related

Std mutex or boost mutex? Which is preferable?

What is the real difference between std::mutex and boost::mutex? Which one is faster in terms of implementation and compilation? Are both of them portable?I read my questions related to it but there is no clear mention of difference . std mutex is supported only since c++11 so the older compilers dont support it . Are boost mutex supported by older compilers or not? If the foremost condition requires the code to be portable , then what should be prefered?
As a default choice you should prefer std::anything to boost::samething because it's a part of standard library and hence is more portable since it doesn't introduce external dependency.
You can't really compare std::mutex and boost::mutex in general because there is no one and only std::mutex, it's implementation depends on the standard library implementation that you are using which usually is a part of your toolchain.
There might be a case when you discover using empirical evidence that std::mutex you are using is in some regard "worse" than boots::mutex. In this case it might be reasonable to switch to it, but only if it's really justified and you have an actual evidence (e.g. performance measurement) of that. Even then it seems like a last resort. It might be better to switch to a different standard library implementation or to a different toolchain or upgrade your current one if possible.
Consider boost as a laboratory for prototyping std features. Many std facilities were originally implemented on boost. The difference is that std takes care of consistency and forward compatiblity, while boost targets new horizons. Nothing prevents boost from applying breaking changes in forth coming versions, but it also provides answers to more questions than std. My personal preference is std first - when possible - and boost next - when needed. I generally avoid pre c++11 platforms, unless I am forced to face.
# std::mutex for me every time, for the reason #Henri states it is (obviously) part of the C++ standard so you can rely on it being available everywhere.
Using boost, on the other hand, means that you have to link against the boost library. While this is widely available and offers a number of handy extra features it's quite heavyweight and you wouldn't want to pull it in just for this.
Also, std::mutex may be faster. The cross-platform nature of boost means that things that rely on OS support (which would include mutexes) can sometimes be less efficient. But this would not be a major factor in my thinking.
But if measuring performance is important to you, you should run your own benchmark. You can do this (roughly) over at (say) Wandbox - they support the boost library there.
The focus of Boost is trying new techniques and introducing new capabilities. The focus of the C++ standard is specifying requirements in a way that (in most cases) can be implemented portably. A number of features from boost have found their way into the C++ standard, but were often changed quite a bit in that transition - to improve portability, sometimes improve reliability, etc.
If your implementation (compiler and library) is C++11 or later, and you intend to not to port to older implementations, then definitely use std::mutex. It is part of the standard, from 2011, so preferable. No need to rely on third-party libraries. You will only need boost if you need bleeding edge features of boost that the C++ standard does not support (which means things other than mutex).
Some exceptions to the above: there are some features of boost (including related to threading and mutexes) that haven't made their way into a C++ standard, and some features in the C++ standard that are not in boost.
If you need to use (or support or port to) an older implementation, then consider using boost::mutex. You will, in most cases, need to install a version of boost separately, with your chosen implementation (some compiler versions have shipped with a version of boost, but don't rely on it). If there isn't a version of boost that works with your compiler/library, then (to state the obvious) you will not be able to use boost::mutex.
Boost has had the thread library (which includes mutex) since about version 1.25.0, which dates from late 2001. Which suggests boost is an option if your compiler is no older than (rough guess) early 2000s.
If you need to support an implementation that is significantly older than the early 2000s, then you may be out of luck using boost::mutex, and will need to resort to other libraries/frameworks or get your hands dirty writing OS-specific code.

WIll Boost have a version with a modern-C++ "cutoff"?

With C++17 now published, even more of Boost's libraries are now covered by the standard library: optional, variant, any, ASIO (in the Networking TS), coroutines (in a TS) and more. This, in addition to the gobs and gobs of Boost stuff already in the standard, see this answer. I realize that some of the standardized versions have slightly different design space choices than Boost's, but essentially it's the same.
Given this fact, are there or have there been plans to release an alternative version (or just - a new mainline version) of Boost which:
Foregos most or all of these features as Boost libraries
Lets the rest of the Boost code rely on their availability in the standard library
Lets the Boost code rely on the language being at least C++17, to make life easier and the code more scrutable to developers
?
If not - is this because of the importance of the Boost design choices? Too much hassle? Fear of "project bifurcation"?
Note: This is an informative question, so please don't provide your opinion or whether this would be a good idea or not.
Boost has better implementation than many currently existing implementations of standard C++ library.
Note that:
Some issues might be fixed in the latest versions of compilers, I didn't recheck everything before writing this post.
Boost is quite conservative and support many old compilers. Even if the latest compiler has everything fixed, older version still have to work.
With regards to Unicode, I assume C++ programs will try to follow UTF-8 Everywhere.
Boost.Filesystem vs <filesystem>
Windows has no support for Unicode in both C/C++ runtimes e.g. you cannot switch standard library to Unicode-aware narrow character set (UTF-8). As the result std::filesystem::path always assumes non-unicode encoding when used with char sequences. There is std::filesystem::u8path for this, but writing std::filesystem::path p = some_char_sequence imo is way too easy. Any codebase that uses std::filesystem and supports Windows will have to battle this constantly.
Boost.Filesystem allowed user to specify locale to be used for path objects. Boost.Locale could be used to create UTF-8 locale on Windows, eliminating this issue. Std.filesystem does not allow you to do this.
Boost.System vs <system_error>
On Linux with glibc:
std::error_category::message is not thread safe, although it should be. Boost.System at least tries to provide thread-safe implementation for every platform.
System category is not able to test for equivalency with standard error conditions.
On Windows (MSVC) it is broken in multiple places:
Error messages returned by std::system_category have annoying "\r\n" at the end, which does not happen anywhere else. Boost.System explicitly trims those.
Comparing addresses of std::error_category does not work for generic and system categories if used cross-dll. Boost.System never had this issue.
Error message is returned using current user enconding (never UTF-8). Technically this is allowed since standard does not specify encoding used here, but it doesn't help anyone. Although Boost.System did the same (should not be mentioned here?).
Standard error categories are static-local singletons and thus register destructor through std::atexit. When category is accessed for the first time from another atexit handler. This might be a problem and can cause deadlocks (as any implicit locking). I had experience with this in the past.
System category is not able to match WinAPI error codes against POSIX error codes the same way Boost.System does this (something that was the whole point of this facility in the first place).
On MSVC12 (Visual Studio 2013) comparing error categories does not work across dlls. This is one of compilers supported by Boost. Boost.System had no such issues.
The sad part about <system_error> is that <filesystem> and future networking library (ASIO) both rely on it heavily, so both get a little bit broken on Windows.
Boost.Thread vs <mutex>, <condition_variable>, <shared_mutex>.
Until recently on Windows and MSVC std::condition_variable and std::mutex could cause deadlock when instantiated in a dll due to using lazy initialization internally. With MSVC14 (Visual Studio 2015) this should be fixed at least for std::mutex since it was rewritten to use SRW locks internally, but I am not sure about condition variables. MSVC12 (Visual Studio 2013) definitely has a lot of bugs here.
If you need a reader-writer lock, it might be very important to know if it favors readers or writers. Standard std::shared_mutex does not allow you to specify this behavior and according to the original proposal this was done because there is an algorithm that allows implementation to favor neither and try to prevent starvation of both (somewhat "fair" lock). Original implementation e.g. boost::shared_mutex follows this algorithm and is not based on pthread_rwlock_t (which usually favors readers due to requirements of POSIXas std::shared_mutex. Imo this means std::shared_mutex has a poor implementation on many systems. Although Boost implementation is not the fastest one either.

Fencing in old C++ compilers

I have a multithreaded application which I need to compile on gcc 4.4, I am not allowed to use the c++0x flag.
I want a variable to behave atomically but unfortunately w/o the C++0x flag I am unable to use atomic<T> in C++.
I tried boost::atomic but it gives me an error saying
ISO C++ forbids declaration of "atomic" with no type
Is there any other way to achieve atomicity under these conditions, can I use fencing - if yes then is there a guide or commonly used commands to achieve fencing in old C++.
As advised by Sam Varshavchik in the comments above, using POSIX std::mutex we can protect the variable in multithreaded application.
std::mutex is an overkill but it's the best we have for gcc 4.4.
C++11 atomic does a better job at solving this issue but is available only on more recent compilers.

Best practice for using the 'volatile' keyword in VS2012

Since upgrading our development and build environments from VS2008 to VS2012, I am confused about the implications of using the volatile keyword in our legacy codebase (it's quite extensive as there is a much copied pattern for managing threads from the "old" days).
Microsoft has the following remarks in the VS2012 documentation:
If you are familiar with the C# volatile keyword, or familiar with the behavior of volatile in earlier versions of Visual C++, be aware that the C++11 ISO Standard volatile keyword is different and is supported in Visual Studio when the /volatile:iso compiler option is specified. (For ARM, it's specified by default). The volatile keyword in C++11 ISO Standard code is to be used only for hardware access; do not use it for inter-thread communication. For inter-thread communication, use mechanisms such as std::atomic<T> from the C++ Standard Template Library.
It goes on to say:
When the /volatile:ms compiler option is used—by default when architectures other than ARM are targeted—the compiler generates extra code to maintain ordering among references to volatile objects in addition to maintaining ordering to references to other global objects.
I take this to mean, that our existing code won't break but won't necessarily be portable (not a problem for us).
However, it does raise these questions, on which I would like some advice, if possible:
Should we remove uses of volatile qualifiers in our our code and replace with C++11 ISO Standard compliant equivalents, even though we would not port the code away from MS?
If we don't do the above, is there any downside?
I appreciate that this is not really a specific programming problem but we're embarking on some quite major refactoring and I would like to be able to offer some sensible guidelines for this work.
If you have the time for it. The benefits are not that great - C++11 atomics may allow more precise control over precisely what kind of synchronization you need, and have more clearly defined semantics, which may allow the compiler to optimize the code better.
In theory, but very very unlikely, a future version of the compiler might drop support for the MS-style volatile completely. Or one day you actually do want to port away from the MS compiler, even if you stay on Windows. If you're now doing refactoring, that might be a good time to do the work of replacing the volatiles with atomics, saving you from doing the work in the future.

In c++ how do you declare a binary semaphore?

I am trying to declare a binary semaphore in C++.
Is there a way to do it by using Semaphore X; ?
What is the header you need to include?
Sorry ... I am using unix g++
The C++ language and standard libraries do not have any concept of semaphores, or even threads. The answer depends entirely on what platform you're working on; for instance, the Windows and Linux system APIs have support for semaphores.
Since C++2003 will be around for a while have a look at Boost.Thread. You won't find a semaphore in there, but that is probably too low level for what you are trying to do anyway.
If the compiler you're using implements (at least the threading part of) the C++11 standard library, you'd use std::mutex X;, or possibly std::recursive_mutex X;, std::timed_mutex X; or std::recursive_timed_mutex X;, depending on what capabilities you want (lacking a statement to the indicate otherwise, I'd guess you want std::mutex).
With an older library, you'd probably want to use the pthreads equivalent. If you need to support Windows (which doesn't include pthreads natively), you could use Anthony Williams's pthreads-win32 package. This has two good points: first, it's native to Posix and Posix-like systems (e.g., Linux), and second, although it uses slightly different names, the basic idea is almost like what's in the C++11 standard library, it should be pretty easy to change to that when your compiler supports it.
Since C++20 this is now possible in standard C++. See https://en.cppreference.com/w/cpp/thread/counting_semaphore for reference and an example. It is supported by compilers: g++ 11, clang 11, msvc standard library 19.28