Can someone please explain in what scenario's it would be beneficial to use std::mutex vs pthread_mutex_t. I dont understand why we would ever use pthread_mutex_t. Thanks
The pthread_mutex_t is a POSIX solution (available for linux and other UNIX systems) that existed before c++11 introduced synchronisation primitives into the c++ library. You should use std::mutex now, amongst other things it is more cross-platform (can be used under Windows also).
std::mutex is just a thin wrapper around pthread_mutex on systems supporting pthreads.
In general, the operations on the std:: thread primitives are quite limited vs the native versions (pthreads or windows threads). If you don't need those features, you should always use the std:: versions, but if you do need the advanced features, then you have no choice but to use the native version.
native handle() method exists for exactly this reason.
std::mutex is from standard library, so if you use it your code will compile also on platforms where pthreads are not provided. For example under windows std::mutex uses native WinAPI mutex implementation.
Its best to always use std::mutex.
See pthread_mutexattr for an idea of the other flavors of POSIX mutexes available besides the default. Though one of the main ones-- recursive vs. nonrecursive-- is available with std::recursive_mutex, this is not true for things like BSD priority ceilings, etc.
Related
When implementing condition variables into a Win32 C++ program, would it be better to use Win32 functions, classes, and data types (e.g. CreateThread, SleepConditionVariableCS, WaitForSingleObjectEx, ReleaseMutex, CONDITION_VARIABLE) or those from the C++11 standard libraries (e.g. thread, wait, join, unlock, condition_variable)?
Since the answer to this question is probably not binary, what considerations should one take into account when making such a decision?
The C++ synchronization mechanisms are designed to C++ principles. They free their resources in the destructor, and they also use RAII to ensure safe locking. They use exceptions to signal errors.
Essentially, they are much harder to use incorrectly than the function-based native Windows API. This means that if you can use them (your implementation supports them), you always should use them.
Oh, and they are cross-platform.
One consideration should be what your compiler can handle. For example, when you install MinGW on Windows, you can choose whether to install the API for POSIX threads or Win32 threads. On the other hand, if you use TDM-GCC, you should be aware that versions 4.7.1 and lower use Win32 threads, while versions 4.8.1 and higher use POSIX threads. And as woolstar mentioned above, if you're using Microsoft's compiler, you should check to see whether the bugs in its support for these classes have been worked out.
If your compiler supports POSIX threads, you can use the C++ thread classes of the Standard Library (e.g. thread, mutex, condition_variable). If your compiler supports Win32 threads, you can use the Win32 thread functions.
In my case, I originally had TDM-GCC 4.7.1 and tried to use the C++ Standard Library classes, but that didn't work (for reasons explained above). So I installed MinGW by itself and chose "posix" in the "threads" option of the installer. Then I was able to use those classes.
New to linux and c++.
I wante to create an application that only needs to run on linux (ubuntuz) and i need to use basic read-write locks.
I saw that there are a few libraries that give "concurrency capabilities".
e.g. to use mutexes, there are at least 3 options:
pthread_mutex_lock (pthread.h)
boost::mutex
std::mutex (mutex)
could someone explain the differences between the various approaches?
pthreads is a C-API and is available on all posix conformant systems (pthreads stands for Posix THREADS).
boost::mutex is a C++-only API that depends on the "boost"-library (you cannot use it in C-code; you add a dependency on "boost")
lots of features from boost will eventually end up in the C++ standard library, e.g. threading; with C++11 you have std::mutex, but you will need a compiler recent enough to support that recent addition. e.g. if you want your application to be backportable to older distributions you might want to avoid it.
std::mutex is part of the standard library. Every C++ compiler/library vendor is free to implement it in any way they like. A library implementation for Posix will more likely than not just use pthreads under the hood, while for instance a Windows library would use the Windows API primitives.
If you can, use std::mutex, but if you don't have C++11 support yet, write your own SBRM classes that wrap the pthread mutex and locking primitives, or use Boost if that's feasible (e.g. if your project already uses Boost anyway). It'll all come down to the same thing anyway.
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
I have seen tutorials on the internet for making multithreaded applications in C++ on Windows, and other tutorials for doing the same on Linux, but not for both at the same time. Are there functions that would work even if they were compiled on either Linux or Windows?
You would need to use a library which contains an implementation for both pthread on Linux and the Win32 threading library on Windows (CreateThread and friends).
Boost thread is a popular choice which abstracts the system away.
You can use POSIX threads and use this library to get pthreads on Windows.
http://sourceware.org/pthreads-win32/
(This is probably only a good option if you're already very used to doing threading on a POSIX system...)
You can start with boost::thread. The library provides an abstraction layer and works internally against native threading APIs of each supported platform.
You should be looking at the boost library.
Or you can use ZThread, its pretty lightweight as opposed to boost::thread
You can also look at QThread from Nokia's Qt
A portable option is also present in TBB's threads. Of course, TBB encourages you to use the concept of tasks rather than threads, but if you ever need just threads, then this example could help (you'll have to convert the deprecated headers and thread declarations to the new ones).
I suggest TinyThread++ or TinyCThread.
I started using TinyCThread, I found it amazingly simple and it supports many systems including Windows and Linux.
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?