C++ Multi-threading? - c++

I've decided to make a game in C++ recently and I figured out that there isn't multi-threading support in C++ :( There are libraries but they are platform dependent and that's not really good. Is there any way to do this platform-independent in C++?

C++11 has built-in threading support (as part of the language as well as the standard library).
http://en.wikipedia.org/wiki/C%2B%2B11#Multithreading_memory_model
http://en.wikipedia.org/wiki/C%2B%2B11#Threading_facilities
Also, boost::thread (boost::asio I believe) does offer (more or less) platform independent threading support (and it's not the only library that offers this).

Related

How does the standard threading library compare to Boost’s?

I am re-writing a bit of legacy code in C++ 11 and wanted to make the processing more concurrent. I have read about C++11 threading library but wanted to see if anyone has used this and if you'd able to share you thoughts on how easy it is to implement?
Between Boost threading and this library, which one is more preferable and why?
Boost threading library is the same than the standard one (if you activate the new interface) but it adds features which are currently proposed as extension for C++14/17. It also propose more synchronization tools than the current standard or even C++14 draft.
What you need to know is that the standard and boost libraries are actually low-level concurrent constructs, they don't provide yet higher-level constructs, but there is work by both the standard commitee and Boost developers to add such constructs.
I recommand reading the book "C++ concurrency in action" which describe in depths how the C++11 threading library work and what it don't provide too (like thread pools implementations).

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?

Is PThread a good choice for multi-platorm C/C++ multi-threading program?

Been doing mostly Java and smattering of .NET for last five years and haven't written any significant C or C++ during that time. So have been away from that scene for a while.
If I want to write a C or C++ program today that does some multi-threading and is source code portable across Windows, Mac OS X, and Linux/Unix - is PThread a good choice?
The C or C++ code won't be doing any GUI, so won't need to worry with any of that.
For the Windows platform, I don't want to bring a lot of Unix baggage, though, in terms of unix emulation runtime libraries. Would prefer a PThread API for Windows that is a thin-as-possible wrapper over existing Windows threading APIs.
ADDENDUM EDIT:
Am leaning toward going with
boost:thread - I also want to be able
to use C++ try/catch exception
handling too. And even though my
program will be rather minimal and not
particularly OOPish, I like to
encapsulate using class and namespace
- as opposed to C disembodied functions.
Well, pthreads is the old posix standard for writing threaded programs. Its the lowest level threading routines, so its a good choice for cross-platform threading.
However, there are alternatives:
boost::thread - an STL style
threading library
Intel's Thread
Building Blocks
OpenMP -
both these are a higher-level way of
writing threaded apps without needing
to do any threading calls.
As the latter are all fully supported on all platforms, (pthreads requires a bit of compiler settings as its only part of Windows posix subsystem, unless you want to use Pthreads-w32), then perhaps the latter ones are a better choice. boost::threads are more like a threading library, the other 2 are high-level ways of achieving parallelism without needing to code 'threads', they allow you to write loops that run concurrently automatically (subject to common-sense conditions)
Boost::thread is not a C compatible library though.
edit: cross-platform abilities of the above:
Intel TBB is cross-platform (Windows*,
Linux*, and Mac OS* X), supports
32-bit and 64-bit applications and
works with Intel, Microsoft and GNU
compilers.
OpenMP depends on the compiler you want to use, but GCC and/or Intel compilers have supported OpenMP Windows, Linux and MacOS.
If you need your code to be truly portable then it may be best to stay away from the various libraries that scatter the internet. At some point you'll find a platform they don't support and will then have to create your own branch.
This is also not a hard problem to solve and can be a good exercise for creating cross-platform code.
I'd suggest you create a class, e.g. CThread, that has separate .cpp implementations for each platform and a pure-virtual execute() function that is called after your thread is constructed/run.
That allows all of your thread-creation and sleep/shutdown/priority code to be implemented using the most appropriate API for the platform. You may also need a header (e.g. ThreadTypes.h) that contains defines/typedefs for each platform.
E.g.
// ThreadTypes.h
#if defined(PLATFORM_WIN) || defined(PLATFORM_XBOX)
typedef DWORD ThreadID
#elif defined(PLATFORM_PS3)
// etc etc
#endif
This is how I have written all my cross-platform threading code for platforms such as PC/PS2/PS3/360/Wii. It is also a good pattern to follow for things like mutex's and semaphores, which if you have threads you're certain to need at some point :)
Nope, pthreads aren't normally available on Windows. (There are a few attempts at implementing it, but it's not supported by the OS directly, at least.)
If you're writing C++, Boost is, as usual, the answer. Boost.Thread has a portable (and safer) threading library.
In C, the simplest solution is probably to wrap write a common wrapper for both pthreads and the Windows threading API.
I will bet on ZThread
Simple API, easier to use than PThreads and FREE
Have a look at ting also:
http://code.google.com/p/ting/
It is cross platform between Windows and Linux. No Mac OS support yet.

If ANSI C++ doesn't support multithreading, how can unmanaged C++ apps be multithreaded?

I have heard that C++ offers no native support for multithreading. I assume that multithreaded C++ apps depended on managed code for multithreading; that is, for example, a Visual C++ app used MFC or .NET or something along those lines to provide multithreading capability. I further assume that some or all of those managed-code capabilities are unavailable to unmanaged applications. But I have read about unmanaged multithreaded applications. How is this possible? Which of my assumptions is false?
It is wholly up to the operating system to provide support for multi-threading. On Windows, the necessary functionality is available via the Win32 API. Frameworks such as MFC provide wrappers over the low-level threading functions to simplify things, while of course .NET/CLR has its own managed interface for accessing Win32 multi-threading capabilities.
A good explanation is offerred in this article (Multithreading in C++).
Why Doesn’t C++ Contain Built-In
Support for Multithreading?
C++ does not contain any built-in
support for multithreaded
applications. Instead, it relies
entirely upon the operating system to
provide this feature. Given that both
Java and C# provide built-in support
for multithreading, it is natural to
ask why this isn’t also the case for
C++. The answers are efficiency,
control, and the range of applications
to which C++ is applied. Let’s examine
each.
By not building in support for
multithreading, C++ does not attempt
to define a “one size fits all”
solution. Instead, C++ allows you to
directly utilize the multithreading
features provided by the operating
system. This approach means that your
programs can be multithreaded in the
most efficient means supported by the
execution environment. Because many
multitasking environments offer rich
support for multithreading, being able
to access that support is crucial to
the creation of high-performance,
multithreaded programs.
Multithreading in C++ does not require managed code.
In very much the same way that C++ does not provide native support for displaying graphics or emitting sounds or reading input from a mouse, the operating system that's being used will provide a C++ API for utilizing these features.
It's not a matter of C++ not being able to do it. It simply hasn't been written into the C++ standard yet.
Some of your assumptions are not quite right. The operating system (I'm talking about win32 since you mention .NET) provides support for threading. There are lots of good threading libs. that build ontop of the OS functionality in C++ to make multithreading "easier" :) -- pthreads for example. Here is more at MSDN.
The ISO standard for the programming language C++ neither defines nor prohibits multithreading. An implementation is allowed to provide extensions if it wishes. A program is allowed to use implementation extensions if it wishes, and then the program will only run on systems that provide those extensions.
For comparison, the ISO standard for the programming language C++ neither defines nor prohibits the use of a mouse. A program is allowed to use implementation extensions and then it will only run on systems that provide those extensions. For another comparison, the ISO standard for C++ neither defines nor prohibits UTF-8, so your program can depend on Latin-1 and then your program will only run on systems that provide Latin-1.
Native C++ does not offer "built in" multithreading support simply because it was not intended to, or in fact, needed.
Your misconception is that this is a fault, while it is in fact a strength of the language. By being "oblivious" to multithreading, C++ seamlessly integrates with the MT support offered by the OS your code will compile and run on, thereby offering much more flexibility and efficiency than if it came with it's own "MT baggage" so to speak.
You mention MFC and .NET as examples - be aware that these libraries/wrappers are merely a layer over basic Win32 API's. Using C++ as intended will provide you with efficient code that will run multithrededly on ANY OS, as long as you seperate the logic from the OS-specific MT API calles (i.e thread creation etc), so that porting between OS's is greatly facilitated.
Unlike Java, which defined language constructs and JVM specs, the C++ standard is oblivious to threading (so is C). As far as these languages are concerned, anything thread-related consists of function calls to OS functionality. Libraries compiled for multithreading simply make sense of the same calls, but from a language perspectives they are plain old code.
I think you misunderstand the definition of 'managed' code. 'Managed' code is a Microsoft-specific term meaning code that is uses the .NET framework and thus is subject to the various aspects of .NET. 'Unmanaged' code means code that runs outside that and does not operate through the .NET layer. MFC code is 'unmanaged'; it's merely a spectacularly bad wrapper for the ubiquitous Win32 API (which isn't even the lowest level API available on Windows).
The .NET libraries (including multithreading) are almost all, at some level, interfaces for the more basic system APIs used by traditional, 'unmanaged' applications. There is, generally speaking, no functionality available to 'managed' code that cannot be replicated in 'unmanaged' code with sufficient effort, though the reverse is not true (this is called the abstraction penalty, if you wish to know more). While it may be easier to do in 'managed' code, that's just because somewhere, some 'unmanaged' code is doing it for you, more or less. In the case of a threading API, it is in turn an interface to the operating system kernel, which itself accesses the processor's capabilities to allow a process to run in multiple places concurrently (if using multiple cores; if not, then it's just a pseudo-concurrency).
The C++ standard currently provides no definition of threads (the upcoming C++1x standard does). There are a number different threading libraries available, including those provided by Win32 and MFC, the pthreads library found on POSIX systems, and Boost.Thread, which will use the platform's local threading library.
The next C++ standard (named c++0x) will have support for multithreading.
Will include atomic operations.