Threading on both Windows and Linux - c++

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.

Related

Boost named_condition implementation

What is native Linux API used for Boost named_condition class implementation? In Windows, I guess, this is CreateEvent, I want to know what Linux feature can be used to get this functionality.
Posix Threads Condition Variables

A ThreadPool library in C++

I am looking for a good and stable threadpool library for C++ that's fairly well documented. I know about the Native Windows thread pool API and the newer Vista Thread Pool API, however my program requires some backward compatibility, so perhaps an outside library I can provide with the program is better.
I have looked into Boost's threadpool and it doesn't look bad at all, unfortunatly it is not very well documented.
Does anyone know any other libraries that have a ThreadPool in C++? (for Windows)
A portable threadpool library that claims to be 'production ready'. You may want to check that out.
Intel TBB is another threading library that has some neat stuff. I find the framework for evaluating a tree of expressions in parallell especially nice.
Qt has a threading library with some nice high-level operations like map/reduce etc, as well as low-level threading stuff and thread-pool support.
Qt might be a bit big for you though, but you can use a part of it pretty easily.
Have a look at the ThreadPool and TaskManager classes from the Poco C++ libraries.
With respect to the boost thread pool: this link might be useful: http://think-async.com/Asio/Recipes
There's also ACE which does thread-pooling over networks, so it's a fair bit more complex. (but deserves mentioning here, IMO)

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.

C++ thread/process identifier

Is there a portable way of getting thread and/or process identifier (string, int, ...) with C++?
You have a few ways, but all imply the use of an external library abstracting the thread for you.
Among the popular choices, two are:
The Boost.Thread library. This is the most portable but imply working with Boost, which is a HUGE library
The Qt library. This is less portable and imply to work with Qt, a big library.
If you already use any on these two libraries, I would recommend sticking with it. Otherwise, look at what other tools they provide and make a choice.
There is no portable way when portable means a way that works on every platform for that a C++ compiler exists. Such a way had to be part of the C++ standard, in which case it really would work everywhere (just like the other parts of the C++ standard work everywhere). Everything not in the standard is not guaranteed to work on any platform, unless the platform states to support this standard.
Every solution people have suggested here is a solution that uses an external library and thus can only work on platforms supported by that library; and no library is available for every existing platform.
Probably the one that will get you farthest is POSIX, after all every UNIX like system tries to support at least some POSIX (the more the better), very little can call themselves really being 100% POSIX-compliant platforms (e.g. A/UX, AIX, HP-UX, IRIX, Mac OS X 10.5, MINIX, QNX, Solaris, UnixWare, VxWorks, ... to name a few, there are more of course). However, there are quite a couple of platforms that offer at least some POSIX support, some more, some less and some are almost POSIX-compliant (e.g. FreeBSD, Linux, NetBSD, BeOS, OpenBSD, ... and others).
Windows is unfortunately far away from being one. NT used to be partly POSIX conform, but now it has more or less vanished (Win2000/20003, WinXP, and Vista can still be set into a POSIX emulating mode, translating some POSIX call to internal API calls by installing Microsoft Windows Services for UNIX - SFU 3.5 or higher), however there are ways to get some POSIX functionality on Windows through external libraries as well (Cygwin offers LGPL libraries you can link with your app to enable a fair amount of POSIX functions on Windows).
The advantage of POSIX is not only that it is relatively widespread, but also that it is standardized and you can easily look up the standard on the Internet. Using POSIX calls you can get a thread id and a process id.
I always thought threads were external from C++. In Java, there's a native thread built-in to the language.
You'd have to find a portable thread library.
The only way is to use portable library. Id recommend Qt (it doesn't have to be GUI app) or maybe wxWidgets. If you are developing a game check out SDL
Also check out boost libs they might have something.
You may also use part of ACE library, which implements a platform independent wrapper. Finding PID would be one of the files in the library (maybe ACE_Process/ ACE_Thread).
I'm not sure how portable they are but Posix threads may be another option you want consider. See also here. I agree with Steve's comment--portable to which platforms?
getpid() is a portable way to get the process ID.
I don't think you're going to find a portable method unless it is through a wrapper library. Each threading system (eg. Windows, or POSIX) are going to have their own mechanism.