Portable C++ multithreading - c++

I'm writing a library in C++ language that uses multithreading. Since I'm developing it in windows, I'm using the method and the data structures in "Windows.h" (like CreateThread, HANDLE WINAPI, etc).
Now I would like to make this code executable both in Windows and in Linux; can you suggest to me some threading implementations to do that?
The main requirement of this application is execution speed, so I need some implementation that is fast.
Thank in advance.

Your best bet by far is to use the new std::threads library, this is portable and standardised and written in a modern style.
std::thread my_thread(my_func, my_param);
http://en.cppreference.com/w/cpp/thread
If you don't have access to C++11 (VC10 and >gcc 4.4 should be fine), then the std::threads are more or less a developement of the great boost::threads, the boost library is cross platform and portable (at least it will support major OS include Win32 & linux).
http://www.boost.org/doc/libs/1_49_0/doc/html/thread.html
Finally if you are looking for parallelising algorithms it might be worth your while checking out intel's TBB, that is a modern C++ thread library that provides parallel constructs similar to the std:: algorithms
tbb::for_each(my_contaier.begin(), my_container.end(), my_func);
http://threadingbuildingblocks.org/

As an alternative, a quite portable (*) and relatively non-intrusive library, well supported on g++ and (with an old version) on MSVC is OpenMP.
It is not standard C++, but OpenMP itself is a standard. It let's you paralllelize loops easily:
#pragma omp parallel for
for (int i=0; i!=x; ++i) {
}
It has also tasks and timing capabilities (and more), but in my opinion it's king discipline is above exampled parallel for.
(*) If you stay with the pragmas, it isn't unportable at all.

boost::thread is the solution also std::thread in the new standard C++11.

Boost.Thread
http://www.boost.org/libs/thread

Related

Working with threads in c/c++, across many different platforms

In my understanding, if you use C, then you are bound to use POSIX Threads.
These are OS dependent, and if you use Linux, you have to use <pthread.h>, while if you use Windows, you have to go with <windows.h>.
These things are transferable to C++ as well.
However, if you use C++ and specifically a version after C++11, then you can skip the POSIX threads method, and use #include <thread> and you are off to go.
Is this a correct understanding? Is there something i miss?
Since C11, there is a support of threads directly in the standard C language (using threads.h). Note that mainstream compilers (Clang, GCC, ICC, MSVC) support OpenMP which can be used to parallelize computing codes using multiple threads (typically numerical codes). OpenMP is available in both C and C++ (as well as FORTRAN). Note also that PThreads is supported on Windows as a wrapping library. In pre-C++11, note that there is many portable threading libraries. One famous library is the Intel Threading Building Blocks (aka TBB).
Related question: Multi-Threading support in c11

Cross platform multithreading in C++?

Basically, the title explains it all; I'm looking to make a game in C++ and I want to use multithreading for stuff like the physics engine and keeping the animation smooth on the loading screen. I've seen a few multithreading libraries, but I'm wondering which is best for my application, which will work well on Windows Mac and Linux. Does such a library exist?
You probably want boost::thread or Intels' Thread Building Blocks. I'd recommend TBB but it's not free, I think, so boost::thread for the free option.
If you can use c++0x threads, then use that.
If not, boost::thread is the best free multi-platform library.
My favourite is QThread. Part of Qt library.
Currently my recommendation would be OpenMP (libgomp on g++, IBM XlC++, MSVC++ all support it)
OpenMP offers a simple way of exploiting parallelism without interfering with algorithm design; an OpenMP program compiles and operates correctly in both parallel and serial execution environments. Using OpenMP's directive-based parallelism also simplifies the act of converting existing serial code to efficient parallel code.
See msdn
And GOMP
for starting points
Random quote:
To remain relevant, free software development tools must support emerging technologies. By implementing OpenMP, GOMP provides a simplified syntax tools for creating software targeted at parallel architectures. OpenMP's platform-neutral syntax meshes well with the portability goals of GCC and other GNU projects
Another nice library that includes cross platform threads is poco

Multithreading in C++ ... where to start?

I'd like to start learning multithreading in C++. I'm learning it in Java as well. In Java, if I write a program which uses multithreading, it will work anywhere. However in C++, doesn't multithreading rely on platform-specific API's? If so, that would seem to get in the way of portability.
How can I do multithreading in C++ without causing portability issues? Is boost's thread library a good solution?
As a sidenote - how is it even possible to implement multithreading as a library? Isn't that something that has to be done by the compiler?
If you do not have a compiler that supports C++0x yet (available with visual studio c++ 2010 for example), use boost threads. (Unless you use a framework that already supports threading, which is not the case - you wouldn't ask the question otherwise -). These boost threads became actually the standard in the brand new C++. Before that time C++ itself was thread unaware.
TBB Threading Building Blocks might also be interesting to you if you want to learn other aspects in parallel programming.
Regarding Qt: if you only want threading support it is complete overkill. It has horribly slow round trip times from compiling to result. It is really well designed thought. But not an official standard like the C++0x threads from boost. Therefore I would not take it as a first choice.
In C++, yes threading is platform specific. However, many threading libraries encapsulate the nuances of threading on various platforms, providing a uniform API with which to write your threaded app, so you don't have to worry about platform specific details.
Boost threading library is a very good solution.
I also recommending checking out ACE as well.
Let's start backward:
How is it possible to implement threading in a library ?
It isn't, at least not in (pure) C++. This requires language support (the compiler is only an implementation).
At the moment 2 things are used:
assembly code for some parts (like in the pthread library)
specific compiler instructions for others (dependent on the compiler and platform)
Both are brittle and require a tremendous amount of work for portability. Basically it means lot of #ifdef portions in the code to test for the compiler and targetted architecture, test for the support of some directives etc...
That is why it was deemed necessary to add threading support in C++0x.
How do I do multithreading ?
Even before you choose a library, you should choose a method. There are 2 ways of programming multithreaded applications (and you can combine them):
Communicate by sharing: this means using mutexes, atomic operations, etc... you can use pthread on Linux platforms, but I would recommend Boost.Thread (among others) for its portability.
Share by communicating: more recent, and adapted to distributed computations, this stems from the functional languages. This means passing messages from one thread to another and not sharing any resources. You can use FastFlow or Intel's Thread Building Blocks aka TBB.
You can conceivably merge the two, but it would be better not to. Personally I have found the description of FastFlow totally awesome: it encourages lock-free programming. Also, the main advantage of the second method is that it's better adapted to multi-processes programming and scales to distributed environments.
To begin with, I would recommend focusing on either one and build some applications with it. When you're comfortable you may try out the other, but be ready to start anew, they are that different.
//This program explains how pthread works, here 5 thread are trying to update a global variable simultaneously but with locking synchronization in maintained
#include<iostream>
#include<pthread.h>
using namespace std ;
#define MAX_NO_THREAD 5
int global_sum = 0 ;
pthread_mutex_t lock ; //Declared global lock mutex object
void *print_fun(void *arg)
{
cout<<"\nThread id : "<<(int)arg;
pthread_mutex_lock(&lock) ; //aquiring lock on piece of code
for ( int j=0; j<100000000; j++)
{
global_sum++ ;
}
pthread_mutex_unlock(&lock) ; //reomving lock on peice of code
cout<<"\nGlobal Sum : "<<global_sum ;
}
int main()
{
int i = 0 ;
pthread_t threads_obj[MAX_NO_THREAD] ; //Initializing object array for thread
pthread_mutex_init(&lock, NULL) ; //Initalinzing lock object for thread
int st ;
for ( i=0; i<5; i++)
{
pthread_create(&threads_obj[i], NULL, *print_fun, (void *)i) ;//Initializing threads calling function print_fun
pthread_join(threads_obj[i], 0) ; //Forcing main thread to main until these thread complete
}
pthread_mutex_destroy(&lock) ; //Destroying lock object
}
//compile this program using -lpthread option with g++
//g++ thread.cc -lpthread
also check out
Qt
To offer a suggestion different from Boost, I use Pthreads (or Pthreads-Win32 on Windows). It's a very do-it-yourself barebones library, but provides you with all you need and nothing else. It's very lightweight compared to Boost and you can easily find C++ wrappers around it to give you higher level abstractions.
you might also consider openmp http://openmp.org. Many compilers support it, including MS, GCC/G++ and Intel. Although you don't get explicit control of threads, its higher level abstraction of parallelism is sometimes more efficient (at coding time as well as runtime), and the code is much easier to understand. It's not going to help you much if you're doing GUI work, but for scalable computation it's worth a look.
The Boost Threading Library is probably the best place to start for C++. Gives you threading contructs, as well as all the mutexes and control objects you need to write a real working multithreaded application.
With C++11, "Thread support library" is introduced under <thread> header.
More info could be found from below links
https://en.cppreference.com/w/cpp/thread
http://www.cplusplus.com/reference/thread/
If you're doing this out of interest to improve your knowledge of different programming models and language skills then the Boost library would be a fine way to go. However I would think long and hard about actually building any production applications using multi-threaded C++.
C++ is challenging enough at times to attain correctness without adding the considerable complexity of shared memory multi-threading. Even the most seasoned programmers would agree that multi-threaded programs are extremely hard to reason about and get right. Even the simplest programs can quickly become hard to test and debug when multi-threaded.
Imperative languages such as C++ or Java or C# (with their mutable variables, shared memory and locking/signalling primitives) are very often the least approachable way to try to build multi-threaded applications. There are usually perfectly good single threaded implementation options to accomplish most user-space (as opposed to kernel or embedded) application problems, including on multi-core machines.
If you really want to build reliable "multi-threaded" applications I would suggest you check out functional languages like Erlang, Haskell, F# or Clojure.

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.