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

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

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.

Is c++11 thread platform independent?

I searched for lots of questions and answers, but I really couldn't figure out this issue. Yesterday I have tried C++11 thread on Windows in a Visual C++ project and it works fine.
Does that mean we can use C++11 threads on every platform that has a compiler with C++11 support? Are there any reasons not to use this thread instead of pthread or Windows thread (depending on the platform)?
The C++ 11 thread library still uses threads from the OS and relies on them but it is abstracted in a good way so you will experience almost no differences. The behavior is different only in the detail and you will almost not notice them (only on edge cases and/or on failure). There might be still some platforms out there which don't support everything from std::thread (even in 2015, e.g. on some specific / exotic mobile platforms).
From the C++ Standard:
30 Thread support library
Some functions described in this Clause are specified to throw
exceptions of type system_error (19.5.6). Such exceptions shall be
thrown if any of the function’s error conditions is detected or a call
to an operating system or other underlying API results in an error
that prevents the library function from meeting its specifications.
Failure to allocate storage shall be reported as described in
17.6.5.12.
C++11's thread mechanisms are intended to be cross-platform like any other feature of standard C++. From my understanding, all major compilers intend to support the C++ standard to the best of their ability which means supporting the threading library.
It really depends how well the compiler supports it. I would imagine GCC / VS /Intel have pretty good support by now but then if you are targeting some exotic platform that might not necessarily be the case.
That's been the case with the STL for a while now - it's mostly portable, but it really depends on the implementation.
Just because it's in the standard does not mean it will magically work, even though the chance of it working is much higher than if it was not in the standard.
There will still be other implementations - pthread, boost, whatever. Which one you use depends on your personal preferences, your requirements, etc, etc.
Yes, it is platform independent. It can be (and often is) implemented as wrapper for pthreads, so basically it can be pthreads with different API.

C++0x threading

With the advent of threading facilities in the STL for the new C++ standard (C++0x), will it be better to change existing code that is using POSIX threading or even Windows threading to use STL threading?
You could always hedge your bets... write your own simple threading API that is just featureful enough to do what your application needs to be done, and change your code to target your threading API only. Then you can implement the internals of your custom threading API using Windows or Posix or STL or whatever, and change the implementation whenever you need to without having to touch your entire codebase each time.
By doing it that way, you could start with the STL implementation, and then if it turns out that e.g. Windows has a difficult-to-resolve problem using that, you could just include an alternate Windows-API implementation inside my_threading_api.cpp (inside of an #ifdef WIN32) and you'd be back in business.
A great deal will depend on how much you care about portability, and how much you're taking advantage of features your native API may provide that the standard library doesn't. The standard library threading is sufficiently similar to POSIX that (at least offhand) I can't think of much you'd gain by staying with POSIX (and due to the similarity, porting to use the standard library should usually be pretty easy).
Windows threading is enough different that you're more likely to run into something that will be non-trivial to port to using the standard library, and even at best porting will probably be non-trivial.
Don't change unless you really need it. I assume that your existing code is working well.
There's no telling how long it will be before the C++0x library features are commonly supported, so the answer might well depend on how tied to a particular compiler you might want to be.
You might also want to consider a framework or library that works on top of the native or C++0x library implementation, such as Boost Threads or the Intel Threading Building Blocks and let that library handle the details of whether it's using C++0x features or platform APIs.
It depends.
C++0x threading isn't widely supported yet (I think GCC implements it, but MSVC doesn't, and I don't know when they're planning to add that support, but I might suspect they consider it a low priority feature)
If your code works as it is, why change it?
For new C++ applications, and assuming compiler support, I'd go with C++0x threads, simply because they're standard, and it's a much nicer API than either Win32 or POSIX threads.

Is there any cross-platform threading library in C++?

I'm looking for some easy to use cross-platform threading library written in C++.
What's your opinion on boost::thread or Pthreads?
Does Pthreads run only on POSIX compliant systems?
What about the threading support in the Qt library?
Boost.Thread is the draft for the coming standard threading library of the C++ language. Knowing that, I prefer to use it as it provide some strong guarantees (because it becomes standard).
Update: Now that we have the standard threading libraries, some more precisions. Some boost constructs, like boost::shared_mutex, have not been standardised (but might be later). However the standard library exploit the move semantic better. Good to know before choosing a library. Also, using C++11 threading library requires a compiler that provides it. It's not the case for all compilers today.
Update:
Now [Nov2012] most of the Standard compilers provide C++11 threading library. VS2012, GCC4.8 and Clang3.1 have support for threads and synchronization primitives and atomic operations.
For complete implementation you can also use just thread by Anthony Williams. It is C++11 compliant library supported on Windows/Mac and Linux.
Links for status of C++11 features with various compilers:
GCC 4.8 - http://gcc.gnu.org/gcc-4.8/cxx0x_status.html
Clang3.1 - http://clang.llvm.org/cxx_status.html
VS2012 - http://msdn.microsoft.com/en-us/library/vstudio/hh567368.aspx
There is a threading library coming with C++11. It's built upon the boost threading library. Unfortunately, I seem to remember that there are non-trivial differences between Boost.Threads and what C++11 comes with. Still, if you plan to switch to the C++ standard threading library, I believe Boost.Threads is the closest you can get to now.
I suppose that, under the hood, these libraries will use Pthreads on POSIX systems and whatever native threading support is available elsewhere.
Disclaimer: I haven't worked with either of the two.
Pthreads are running only on POSIX systems. QThread from Qt is a way to go. It is available on platforms: Linux, Mac OS X, Windows, Embedded Linux, Windows CE, Symbian, Maemo.
Also have a look at OpenMP, it's a set of (somewhat standard) pragmas specifications that is supported by most major compilers. The good of OpenMP is that it's simple and that your code can be easily compiled in both single and multi-threaded versions.
Just a simple example:
std::vector<double> a, b;
...
double sum = 0.0;
...
#pragma omp parallel for reduction(+:sum)
for (i=0; i < n; i++)
sum = sum + (a[i] * b[i]);
It's obviously possible to do also more complex things.
I am surprised that nobody mentioned the Intel TBB library (linked to an another answer of mine). Also, a task-based implementation should be preferred over a thread-based.
Qt has pretty good thread support. If you just need to create a thread and run some code in it, QThread is all you need. There are many other high-level classes that can help you with thread pools or even abstract the concurrent execution (the QtConcurrent framework).
List the concerning platforms. If you're only using say, Linux/Mac/Windows, then boost::thread will likely do you fine until C++0x (harhar) provides std::thread.
I have used pthreads for code that work on multiple platforms. To get around the Windows lack of pthreads, I have used the following open source library with great success: POSIX Threads for Windows
wxWidgets has thread classes, and as wxWidgets is platform independent, it might just be the best thing for u.
Boost.Threads is built on top of PThreads on UNIX systems and Win32 Threads on Windows.
The boost library is syntactically simple and all of the hairy business of properly interfacing C++ code with C libraries is taken care of behind the scenes. If you're not very comfortable with C++, however, PThreads might seem more straight-forward with its simple C API.
Qt Threads is also a good library, but because I use several other boost libraries, I'll compile and link against Boost no matter what. I might not always link against Qt. And, well, I just don't want to remember how to use two different libraries.
SDL is simple, cross-platform and has threading support.
Pthread is part of Posix, but not every posix systems will have threads. pthreads is most portable.
What platforms will you support?

Reader / Writer Lock with timeout using conditional variable

How to write a Reader/Writer lock with timeout, using conditional variables in C/C++?
If you're just looking for a library, Boost.Thread might do what you want.
You may take a look at the source of Java's implementation ReentrantReadWriteLock.
Just grab the JDK unpack the src.zip file and search for the source.
There is no support for such things in current standard C++, although C++0x will have some threading support (I haven't checked to see how much). Therefore, any answer would have to be platform-dependent, using platform in a very general sense.
It is possible to write libraries that will behave similarly across different underlying systems, and there are quite a few cross-platform libraries. (These are subject to inefficiencies, of course, if the capabilities of the underlying platforms are different.) There could be a generally accepted C++ threading library that would work on Windows and Unix-based systems (which is almost anything you'd be running on a desktop nowadays), but I don't know of one offhand.
Therefore, this question can't really be answered as asked. It would be necessary to answer it on a particular platform or library, and none is specified. It would make sense if coupled with a request for a library recommendation.
Take a look at the Boost.Thread library. Specifically: shared_mutex and upgradeable_mutex objects.