When writing cross platform applications targeting Windows and any Unix flavored OS, working with different types of threads can be complex. There are two types of threads: detached and joinable. POSIX thread APIs support both Joinable and Detached threads while Win32 multithreading APIs support only Joinable threads.
POSIX threads are available on all Unix based platforms (MAC, Linux …), but are not natively supported on Microsoft Windows. There are some open source alternatives which emulate POSIX threads for the Win32 environment, such as pthreads-win32.
The fundamental difference between Joinable and Detached threads is that Joinable threads can be waited for, while Detached threads cannot be waited for. It is required to wait for a Joinable thread, or else system resources used by it will never be freed. In contrast, you only need to start a Detachable thread and it will terminate on its own.
XPThreads class provides a simple interface for spawning new threads, and at the same time hides complexities involved in using different threading packages. Internally,
XPThreads uses Joinable threads for Windows (only possible threads) and Detachable threads for Unix based OSs (POSIX threads). The code can easily be tweaked, if required, for using Joinable threads on Unix based OSs.
This is my first article on CodeProject. I came across a requirement for providing multithreading support while working on an X-Platform plug-in. One alternative was to use some heavy external thread package which I wasn’t inclined for; hence, I decided to write my own X-Platform thread class.
I have tested this class on Macintosh and Windows, but I strongly believe that this should work alright on any Unix based OS.
Using the code
XPThreads class is simple.
You need to add XPThreads.h and XPThreads.cpp in your project workspace and include the XPThreads.h file in those source files which require to spawn new threads.
The next step is to make a thread callback function. This function should be a global function or a static class member function. It should strictly follow the following function prototype:
unsigned long Entry (void* param)
cout<<"In the thread" << endl;
The second step is to create a new object of
XPThreads and supply it with the function address for the thread entry procedure. This can be done in two ways, as evident below:
In the constructor:
XPThreads* ptrThread = new XPThreads(Entry);
XPThreads* ptrThread = new XPThreads();
The final step is to call
Run() using the newly created
The demo project includes the project files for Windows and Macintosh platforms along with the source code. It demonstrates how
XPThreads can be used on Macintosh and Windows.
Source files include “XPThreads.h” and “XPThreads.cpp” which can be used separately in your application.