C++ thread/process identifier - c++

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.

Related

How can you send data to another process (at the c++ language level only)

Suppose you are developing two application (A and B).
How can you send some piece of information to B from A if you are only allowed to work at the c++ language level (that is including the standard libraries and STL) ?
Now Im thinking std::ofstream and std::ifstream could be a possible solution (albeit a crude one) ? - but what pitfalls is there and can they be avoided ? (how?).
You just cannot. Standard C++17 does not know about any kind of inter-process communication and does not know much about processes (except thru std::system whose behavior is not really specified). Some operating systems don't have any processes and some of them don't have files and some of them don't have pipes.
Read more about operating systems. I strongly recommend Operating Systems: Three Easy Pieces (which is freely available).
Of course, you can read and write a file, but the synchronization between the two processes should still happen (perhaps by running one after the other, in some operating system specific way, so running A then B, and how that exactly happens is OS specific)
Read that C++17 standard (e.g. the draft here) to check.
Some C++17 implementations might not even have any notion of process. You could have a fully compliant C++17 on some embedded system without any operating system dealing with processes.
My recommendation is to be pragmatical, and use some framework like Boost, Qt, ZeroMQ, or POCO (or old Berkeley sockets) which deals with processes and inter-process communication facilities; you'll likely to find a framework supporting the several OSes you really care about (AFAIK, all of Boost, POCO, Qt know about Linux, Windows, MacOSX and offer a common API abstracting them; but you could find some academic operating system which is incompatible with them; in practice, any framework targeting both Windows and POSIX should be practically enough).
With some curiosity, you may find an OS with a good C++17 implementation which has a very weird API (look into GNU Hurd for an example).
If your IPC facility is based on byte streams, look into text-based protocols (perhaps JSONRPC, SOAP, HTTP, ...). They are easier to code and most of them come with some C++ compatible library...
And with a few months of work and a lot of know how, you might even port a recent GCC or Clang to most other operating systems: they are careful to abstract the requirements on the OS in a clever way.
Remember, you could find OSes which don't even have any file system: look into CapROS or Contiki for some recent example, and look also inside tunes.org where interesting discussions related to your topic, in the past century, have been archived. But with some pain (my guess is a few months of work for a GCC or Clang expert), you'll be able to port a recent GCC or Clang to target it to obtain a C++17 cross-compiler targetting them.
IMHO, a C++ standard library which enables only to "open" one single "file" (supposedly named THEFILE) is conforming to the letter of the C++17 standard. AFAIK, you don't have any guarantee that std::ifstream or std::ofstream works successfully.
BTW, current processors are practically multi-core, so it makes a lot of sense to try running A and B in parallel and doing some IPC (in an OS specific way, perhaps abstracted by some framework or library).

are programs coded separately for different operating systems?

If a program was written in c++ to run on Windows, does it have to be completely rewritten to run on Mac OS or a mobile OS?
C++ is a standard language, which means that the source code that you write can be compiled on any platform which has an implementation of the C++ standard. There are two ways you can write C++ programs that can't be compiled on different implementation. First, if you use language extensions that are found on a specific (set of)implementation(s) only. Second, using a library that depends on code that doesn't ship with the standard library(like on OS API).
For the first matter, try always to write standard code. For the second, use cross-platform libraries like Boost, Qt...
Typically, yes, because the program will need to use OS-specific features for windowing and possibly for other features as well (networking, synchronization, etc.) However, many programs try to mitigate this as much as possible by building wrapper classes so that most of the program deals with these wrappers rather than the raw platform-specific tools. To port the program from one platform to another, you just need to reimplement the wrappers using the new platform's tools.
Many programs take this a step further by using prewritten libraries like Qt or Boost to handle some of the cross-platform silliness, but this is (essentially) the above idea at a larger scale.
This depends. In general, Standard C++ is a general-purpose, portable language which can be compiled to run on any system or platform that has a standard-compliant compiler.
However, a lot of the more "interesting" features you might want to add to a typical application are not part of Standard C++. This includes GUIs, threads, sockets, and low-level OS API calls. These are generally not portable, and parts of the code which use these features will need to be implemented separately for each operating system or platform.
Fortunately, this is not as daunting as it sounds, because there are a lot of cross-platform libraries in existence that have already gone through the trouble of doing this. For example, the Boost threading library already has threading code written for different platforms or operating systems, but all of this is abstracted behind a nice uniform API that can be used portably in C++ application code.
Additionally, a lot of non-Standard C++ code still conforms to some standard, such as POSIX, which is supported across multiple platforms. For example, most UNIX-ish systems, including Linux and Mac OS X, support POSIX threads (the pthread API).
If the code itself uses libraries that are supported on all the target platforms then you will only need the appropriate compilers to generate a valid binary for each system.
Software can be written in multiple languages and then linked together. For example, I can code the back-end logic of my application in C++ (often using Boost), and then build two separate front-ends in C# for Windows and Objective-C for Mac. I can link the C++ and C# components to ship for one platform, then link the C++ and Objective-C components to ship for another. That approach will give the most "native" look-and-feel for each platform.
As alternative, I can code the entire front-end in C++ using Qt or WxWidgets. This will run on all platforms, albeit without 100% of a platform's bells and whistles.

Threading on both Windows and Linux

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.

Why POSIX is called "Portable Operating System Interface"?

I have searched hard but still confused why POSIX is called "Portable Operating System Interface", what I learned is that it is some threading library for Unix environment, because when you need to use it under windows you have to use cygwin or "Windows Services of Unix", etc. That's why I am confused why it is called Portable OSIX. I am a professional C/C++ programmer in Windows domain but new in Unix/Linux. Thanks for your answers in advance.
Before Posix, the Unix family tree was becoming very diverse and incompatible. A program written for one Unix was not compatible with a different Unix without significant porting effort.
Posix was one of the attempts to present a common set of utilities and programming interfaces so that your software would be portable to multiple versions of Unix.
Since Posix is about the interface and not the actual OS, it is possible to have a Posix facade on a non Unix OS (such as the Microsoft Windows Services for Unix presenting a Posix facade on top of Windows).
That one or two stragglers have decided to not make it part of their core doesn't not make it any less portable to almost every other important operating system.
POSIX is simply an interface for operating systems that defines concepts like threads, processes, signals, pipes and I/O. This is not the only interface that's portable across multiple interfaces, but is simply one standard. The name was actually defined by Richard Stallman in the 1980s.
The reason for defining POSIX was that many different versions of UNIX were incompatible, because operating systems hadn't agreed on the implementation of threading or processes.
Here are some more links for further research:
The History of Posix: A Study in the Standards Process
POSIX (Wikipedia)
POSIX defines a set of portable C functions, shell, programs that make the life of a programmer easier because given the definitions in POSIX, it is much more easier to write portable code (not just C, but shell scripts too). Imagine if everyone had their own way of doing things!
Not all the operating systems are POSIX compliant, so if you have to develop for those too, you have to do system-specific things. But POSIX is probably the portable standard across different kinds of systems today. Sure, there is ISO C, which is more portable, but then it's hard to write very useful programs in just ISO C!

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.