Threading in BHO/ATL/COM. Winapi or something else? - c++

I writing IE add-on and I'm using ATL for it. I need to create background worker thread so UI thread will be unblocked as soon as possible.
My question is, should I use the lowest possible way of creating thread which is Winapi, CreateThread etc.
Or is there other proffered way of creating worker thread in BHO/ATL/COM projects?
I have to learn this stuff first so I thought I would ask first ;)

There is no need to use low-level APIs unless you need the level of control they offer.
With ATL you already have CWorkerThread, but you could also use other libraries like Boost.Thread if you prefer.

If you are going all the way down to the API, then _beginthreadex is preferred over CreateThread() if your thread will use the CRT. (If you don't know, it probably will)

Typically, you would use boost::thread, the Visual Studio ConCRT, or Intel TBB, depending on how extreme your threading needs are. For the simplest uses, pick boost::thread. For the more advanced uses, pick the ConCRT or TBB. Don't use WinAPI unless you're seriously desperate for some feature not offered in the other libraries. The simple fact is that if you write a library in C++, then going to use the WinAPI for threads is like going back to assembler to write your program. Stay in C++ - use Boost.

Related

MFC multithreading: AfxBeginThread vs Boost.Thread?

I have an MFC application to which I want to incorporate multi-threading. Originally I was thinking of using Boost.Thread because of the general ease of development with boost. However, I'm wondering if there are any gotchas and if I should use AfxBeginThread to be safe in an MFC context?
I found this Microsoft article: Multithreading: Programming Tips. It says:
Accessing MFC Objects from Non-MFC Threads
If you have a multithreaded application that creates a thread in a way
other than using a CWinThread object, you cannot access other MFC
objects from that thread. In other words, if you want to access any
MFC object from a secondary thread, you must create that thread with
one of the methods described in Multithreading: Creating
User-Interface Threads or Multithreading: Creating Worker Threads.
These methods are the only ones that allow the class library to
initialize the internal variables necessary to handle multithreaded
applications.
I was intending to use the threading in a model view presenter context in order to multi-thread some long running presenter tasks. As the presenter needs to communicate with the view I think that most likely qualifies as accessing MFC objects (at least indirectly). Based on that I've decide to go for AfxBeginThread thread creation method for now.
Try to read this article, in the section Concurrent Programming Improvements this is the best way do things on the Windows platform right now.
Boost slows down your builds and contains a lot of extra stuff you don not need.
Also check the MSDN site on parallel programming for more details.
One benefit of using boost::thread is that its interface resembles std::thread's. There are, however, a few differences. If you ultimately want to use std::thread, boost::thread will be a straightforward transition.
Just include the following header file and there should be no problems:
#include <boost/thread/win32/mfc_thread_init.hpp>
#include <boost/thread.hpp>
If you have MFC project, please DON'T introduce boost to it. Use MFC API wherever you can. Since it has some stuff for threading support, you really don't need one extra library (especially boost) for that.
At the time I write this, it is still unsafe because of this issue in Boost.Thread:
http://boost.2283326.n4.nabble.com/Fwd-Thread-Solution-to-conflict-with-MFC-td3477977.html
(short version that anybody trying this discovers soon enough: merely linking with Boost.Thread causes asserts in MFC initialization)

What type of multithreading would be best to learn?

I want to learn multi-threading in C++ but I'm not sure what type would be most useful. The ones I've seen tutorials on are:
Windows native calls
OpenMP
Boost
(I'm sure that there are probably more.)
What is each one's key features and what are they best used for?
Note: I've already done some multi-threading in C# by manually creating the threads, and more complexity of the threading will just make it more fun. :)
I'd start with pthreads if you have more of a C background, or Boost Thread if you are accustomed to more idiomatic C++. Either is reasonably portable and widely used.
How about TBB? It is portable and has easy to use parallel template patterns, concurrent containers, task scheduler and scalable memory allocaturs. TBB will let you manage threads directly, but that is not necessary in most of the cases.
Personally I would stay away from platform specific threads, unless there an urgent need to do something, well, platform specific.
Boost threads is portable and easy to use, but does have neither parallel patterns nor concurrent containers. You would need to manager threads manually, which can get ugly pretty quickly.
PThreads isn't available on Windows and its C. You really want to do multi-threading in C++, not C. RAII mixes well with mutexes and scoped locks.
Another option is PPL in Visual C++ 2010. It is similar to TBB, but as you may guess available for Windows only.
OpenMP is easy to use, but not very flexible. Since you already learned C++, you should use something more serious, such as TBB or PPL. For some strange reason Visual C++ 2010 doesn't support OpenMP 3. Too bad.
If you want to be portable, learn Posix threads. You know, all thread libraries provide more or less the same set of features, so it's up to you, but Posix will give you the basis.
openMP isn't exactly "multi-threading" as you mean it.
WinThreads (Windows) and pthreads (Linux) are POSIX threads and represent probably your best choice to get started. It is important to learn the distinction between processes and threads, then learn about the various memory access models that are associated with them. Next, try concurrency approaches like OpenMP and MPI "threads".
There are some basic concepts that will get repeated. Learn them well.

Pthreads in Visual C++

I'm experimenting with multithreading in Windows and was wondering whether I should
use Win32 API
use POSIX Threads for Windows
Learning Pthreads would be useful if I tried to develop such applications on different platforms - but am I losing anything by not learning Win32 API? Or are both similar enough so that learning one allows me to figure out the other easily?
Use Boost Threads. When C++0x comes along, we will have std::threads. Boost threads has the closest implementation to std threads.
else use pthreads. Pthreads is second closest to std::threads, and formed the main basis of std threads and boost threads.
else do windows threading directly. You can still learn how threads work, and form a mental model of things. It just tends to use synchronization primitives that are a bit non-standard.
If you're going to do much Windows programming, it will pay to learn the basic Win32 threading constructs: critical sections, interlocked functions, CreateThread, WaitFor*Object, etc. These aren't hard to understand, and they translate transparently to equivalent objects in other threading frameworks.
However, for more advanced threading constructs such as semaphores, events, etc., I would use the pthreads library, since the documentation on those tends to be clearer and examples more abundant.
If you're using C/C++, try to use the thread functions of the C/C++ runtime.
If you use the Win32 (or other non-CRT functions to create threads) the CRT might not be initialized correctly in the new thread, causing all kinds of problem (you can read about it here: http://www.codeguru.com/forum/archive/index.php/t-371305.html).
However, most thread-functions (in the CRT, Win32 or pthread) are all based around the functionality to create threads, synchronize threads and destroy threads. In practice this isn't always that easy to use.
In the last year, there is a trend to go to task-based threading (well, I call it that way, I don't know what the official name is). Instead of starting a thread and then executing some logic in it, in task-based threading you create a task and then ask the 'threading logic' to execute the task.
Systems that support this new way of working with threads are:
Visual Studio 2010 (we'll have to wait a few days for it)
Intel Threading Building Blocks
Visual Studio 2010 even has (it seems) special debugging logic to debug the 'parallel tasks'.
Take a look at std::thread
http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2007/n2184.html
And a introduction
http://www.devx.com/SpecialReports/Article/38883
I've found that sticking with pthreads saves my sanity on three counts:
I don't have to fight through
WinAPI docs, which aren't habitually
of any quality.
Anyone that does much with threads
can help out with
pthreads. I've found infinitely more good sources of information about pthreads online.
Whenever I implement anything more
complicated that "Hello World" with
the WinAPI, I find it takes far
longer than one could reasonably
expect. That's just my empirical
input, though.
As far as capabilities are concerned, I've never found pthreads to be lacking in anything, so I don't think I've ever found the need to look elsewhere. There is also a great deal to be said for learning a library that you'll be able to use in any environment you tackle.

PThread vs boost::thread?

Having no experience with threading in the past, which threading technique in C++ will be the easiest for a beginner? boost::thread or pthreads?
I'll go in the opposite direction of everyone else - learn (or at least familiarize yourself with what is available in) pthreads.
Since boost is mainly just a wrapper around pthreads (on posix platforms) it helps to know what is going on underneath. In attempting to be generic, boost leaves the platform specific functionality unwrapped. In order to get to it you need to use the native_handle() calls. In order to use the native_handle() calls you need to know what the platform offers.
Think of it like sockets. There are dozens of socket classes and frameworks. But ultimately they wrap the underlying platform's socket API. Your understanding is always richer by knowing it - and knowing in what ways your class abstractions might have short comings.
Go for boost::thread. It's closely related to the work on the upcoming C++ standard threads, and the interface is quite easy to use and idiomatic to C++ (RAII instead of manual resource management).
boost::thread is a very nice and portable abstraction. I would certainly use it, but also learn the native thread api, like pthreads, so that you know how threading works on your platform.
Boost.Thread uses the RAII concept for locking, which makes things more exception safe and helps to avoid bugs like forgetting to release a mutex.
I'd say they're pretty close to equal in difficulty. The only big difference I see is that PThreads are pretty widely support (if you're concerned with cross platform porting). Another is that there have been quite a few good books on PThreads, though almost all the concepts will translate over to boost::thread, and many other threading libraries.

Standard practice for implementing threads in C++?

I'm looking forward to an interview in C++ in the coming weeks. (yay) So I have been relearning C++ and studying up. Unfortunately I have realized that I've never implemented threads in C++, and am somewhat concerned about a quiz on concurrency.
As far as I can tell, C++ uses pthreads in Linux and some other device in Windows. Is this correct? Is there another industry standard, more OO way to handle threads in C++ that I should be expected to know? And are there any good web resources that you can point me to for practicing and learning threads in C++?
Thanks!
There is a boost threads library which is probably the closest to a standard.
Generally threads are supplied by the OS so you get whatever the OS supplied. Also peoples first exposure to threading is often in a GUI, to allow a background calculation to not block the GUI, and so people tend to use the thread functions supplied by the particular GUI framework (MFC/Qt etc)
Currently C++ is entirely unaware that threads exist. Different OSes provide threading libraries to make them available. The next version of C++, so called C++0x, is going to make a thread library standard. If I were to start a multithreaded app today I would go with either boost threads or the threads that were a part of any package I might be using i.e. QT or WxWidgets.
Well, until C++0x gets here, there is no standard way to do threading in C++. You can use whatever facilities your operating system provides. So yes, if you are on a UNIX-like operating system, you can use pthreads. On Windows, you can use the Windows API.
There are 3rd party toolkits out there that attempt to provide a uniform and portable threading API, e.g. boost threads and QT.
It is also not difficult to write your own portable abstraction layer either. We did this because the boost API didn't have everything we needed several years ago (e.g. no way to set priority).
In windows the only way to create threads is using the win32 API. Every library you may have that creates threads on windows eventually uses win32 CreateThread()
QT Contains a nice C++ wrapper around a thread that is cross platform. Usually a good practice is to have a MyThread class that contains all the nitty-gritty details of setting up a thread, checking for error codes, getting it's exit code and the like. The MyThread class would have a pure virtual function called run() which is intended to actually do whatever you'd want the thread to do. The user of the MyThread class is expected to inherit from it and implement run() this way you can isolate the user of the class from the details for actually creating the thread.
MyThead also needs to have a method start() which initiates the thread. The thread would start at some entry point inside the class (this usually needs to be a static method) and then this eventually leads to the user's run() method to be invoked.
Beyond Qt, wxWidgets, Boost and native, OS-provided threading facilities, you can just Google around for thread libraries for C++. They are probably more portable and lightweight as well (if all you are looking for is threading). However, if you have a need for more facilities and the aforementioned libraries provide them, then go ahead and use them. Boost is especially good, it has other facilities as well, but admittedly it's threading library, as Brian Neal said, is limited in some regards.
For your interview, neither boost nor qt is helpful at all. you could just use them as the high level libs and interfaces, and no one would ask you how to use boost or qt in such an interview.
For understanding threading and mutex etc, see a document from http://code.google.com/p/effoaddon/downloads/list, named EffoAddons.pdf.
Raw source
http://effoaddon.googlecode.com/svn/trunk/devel/effo/codebase/addons/thrd/src/thrd/thrd.cpp,
high level abstract interface
http://effoaddon.googlecode.com/svn/trunk/devel/effo/codebase/addons/thrd/include/thrd_i.h,
and code support wait and signal
http://effoaddon.googlecode.com/svn/trunk/devel/effo/codebase/addons/queue/include/iqb_ops_i.h.
you'd better study something underlying, not just high level interfaces, though write C++.
I've seen several 'real-world' implementations of threading using C++, and they have all been implemented by someone's writing a Thread class to wrap the underlying O/S API
For example, on Windows there's a CreateThread API: your Thread class would pass its this value to the void* lpParameter parameter of the CreateThread API; and your LPTHREAD_START_ROUTINE, which you implement as a private static method of the Thread class, then needs to cast void* back to Thread*' in order to get theThread` instance.