MFC multithreading: AfxBeginThread vs Boost.Thread? - c++

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)

Related

Qt Concurrent or std::async for new code?

I'm considering two options to run asynchronous code: Qt Concurrent and std::async. Given that I'm writing a GUI app with Qt, it makes sense to go with Qt Concurrent. However std::async also seems good and supported by all major compilers.
Should I use Qt Concurrent or std::async for new code? What else should I look for when comparing the two?
Given that I'm writing a GUI app with Qt, it makes sense to go with Qt Concurrent
I would say, it is not so simple. I would personally utilize the standard library as much as I can. However, there are constraints to take into account:
Do you need to support your software on platforms not supporting at least C++11?
If the question is yes to that, using Qt solutions is a better option in a Qt based software. That being said, even for that, you could have different Qt solutions depending on your need. One is the thread weaver from KDE, but let us not go that far for now...
Another question, that you could ask from yourself:
Do you already have an existing code base where that is used throughout?
Depending on the answer, this could also provide further aspect for the decision, whether you prefer consistency, or forward thinking.
There is also another question here to be asked:
How much of QtConcurrent do I need?
Depending on the exact answer, it may or may not be a better alternative. Note that, not every functionality of QtConcurrent is in the standard library just yet, for instance something like QFutureWatcher with the Qt signal-slot mechanism.
So, yes, as a Qt user, I would suggest to use the standard library as much as possible. These days, Qt even explicitly depends on them, so will not run on platform not supporting it. Also, the general direction put seems to be this in Qt Project proper. For instance, lots of stuff got obsoleted in the QtAlgorithms, but that is just one of those.
Qt Concurrent lets you run a function in another thread using QtConcurrent::run(). So i think you can only compare QtConcurrent::run() with std::async.
Qt Concurrent is so sophisticated and has many useful features. It includes APIs for parallel list processing and lets you create multi-threaded programs without using low-level threading primitives such as mutexes or semaphores. It also adjusts the number of threads used according to the number of processor cores available.
I think using Qt Concurrent is so cool because of its high-level APIs and ease of use.

Is there a common design pattern or object oriented approach used to encapsulate thread behaviour?

I have recently been using pthreads on Linux and want to start looking into using boost threads in the near future. I have never used MS visual studio so I don't know the approach there but I (have to) use Embarcadero C++ Builder (formerly Borland) one of the few good things I find with it is that is has a built in class TThread. This is a class that you can derive from to give nicely encapsulated data and start and terminate functions. I prefer this approach than the pthread way of passing functions and void* being passed into the thread create function. I was wondering if there is some kind of design pattern or structure that is commonly used to provide a more object oriented that encapsulates the functionality of threads in this way? I can try and create it myself, but I cannot be the first person to desire this kind of approach and wondered if there was a "standard" way of achieving it.
Edit: Alternatively, if this is a very bad idea perhaps an illustration of why?
I would consider that the most standard approach would be using the standard thread library (closely related to boost::thread, not 100% the same). I would avoid redesigning what has already been designed, reviewed and verified by a committee of experts.
Also note that for the kind of operations that you mention in the comment you might want to take a look at the future part of the standard library (again similar to the boost counterpart), and in particular to the std::asynch function.
I like the way boost::thread is designed (I saw a similar design in the threading library from Rouge Wave). Basically a thread is started by passing a function to be executed and latter that thread object can be used to join that thread. pthread is very similar in design, but boost::thread is much easier to use.

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

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.

What is easiest way to create multithreaded applications with C/C++?

What is the easiest way to create multithreaded applications with C/C++?
unfortunately there is no easy way. Couple of options: pthread on linux, win32 api threads on windows or boost::thread library
There is no easy way to create a multithreaded application in any language.
Just to mention it because it hasn't been mentioned: a compiler with OpenMP support (http://openmp.org/wp/)
Qt has a pretty
threading support and documentation
but as others have cautioned this is not for beginners. The doc link I gave itself points to a short reading list
pthreads!
https://computing.llnl.gov/tutorials/pthreads/
There is no simple answer to this. It depends very heavily on what you hope to gain from multithreading, the platform/compiler, and which threading model you want to use. Every threading API has its pitfalls.
And just because no one has mentioned it so far, OpenMP is another option that is supported in many modern mainstream compilers and is intended to simplify the use of concurrency.
http://openmp.org/wp/
It's been a while since I worked in C++ and I haven't seen the Boost threading support, but I found it very helpful to encapsulate semaphore services provided by the OS, usually either POSIX or Win32, in simple classes that would acquire locks, and release them in the destructors, making their use fairly simple.
void operateOnSharedResource(SharableResource & foo) {
MutexLock lock(foo.getMutex());
// do stuff to foo
// implicit call to MutexLock dtor performs release
}
Ultimately there are lots of simple tricks like this to ease thread programming and I'd be surprised if Boost didn't have something like this by now (EDIT: It does and it's documented in Lock Types).
Regardless, the main problem with writing multi-threaded code isn't going to be solved by any third party library, and that's understanding where your code can be parallelized usefully, and where shared resources are going to be touched and must be accounted for. Here's a few rules of thumb I use when writing multi-threaded code.
Try to minimize the number of shared resources
Try to encapsulate shared resources in class wrappers that make all operations atomic.
Make worker threads as simple as possible
Proper encapsulation really does wonders for writing safer multi-threaded code, because the fewer things you can see, the fewer things can have a race condition.
I'm not sure about the easiest, but IMO the most user-friendly threading library is the one included in the Poco C++ project. For a preview have a look at the Thread.h header file.
The C++0x specification includes threading facilities (one of my favorite new features). Soon it won't matter what OS you're compiling for! Just look how easy it is to create a new thread and join back to the creator thread:
#include <thread>
#include <iostream>
class SayHello
{
public:
void operator()() const
{
std::cout<<"hello"<<std::endl;
}
};
int main()
{
std::thread t((SayHello()));
t.join();
}
Visual Studio 2010 is implementing parts of C++0x but we're still waiting on the threading facilities.
Boost.Thread is relatively easier because it's portable, well-documented and has high-level API such as scoped_try_lock.
Besides the ones already mentioned, ACE is another popular and widely deployed C++ framework that provides thread encapsulations across multiple platforms. It's style of C++ isn't as modern as Boost.Thread, for example, but it is quite mature.
I would say with Qt. Qt Threads and Qt Concurrency are probably worth googling.
Posix Thread is quite good, they also come with great documentation and tutorials.
Not as easy as java threads, but still quite good.
The easiest way is by avoiding/minimizing mutable shared state.
Once you have mutable shared state, you need to deal with locking which is where the bulk of the difficulty in writing multi-threaded programs exists.
This depends entirely on what you're doing. If you can fit what you're doing into OpenMP then that is the way to go. Otherwise you may want to look at Intel's TBB. TBB offers several workflows which you should be able to fit into, but the library is dual licensed and you may not be able to accept either license. If both OpenMP and TBB are out, then you should consider your operating system's thread pools abilities.
At some point you may need to bite the bullet and use Boost.Thread. If so, you'll want to look at what makes multithreading in C++ hard (good to read even if you're not using C++0x: "It's not the threads themselves, it's the communication that causes problems. Mutable shared state introduces implicit communication," page 3).

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.