Re: multithreaded c++ question
Chris Roth wrote:
I'm using VS.net 7.1 on Windows XP.
If your question is specific to win32, you would be better off posting
to a windows specific ng.
comp.programming.threads is more on-topic for generic thread issues.
As for the C++ standard, there is no support for threads, all support is
vendor specific. However, the next revision of the standard will have
thread support.
I have a class that hold a container of doubles. One function (foo) for
the class calls a sub-function (bar) for each of the doubles. I'd like
to multithread foo so that the bar sub-functions can run on multiple
threads. I'd like to imlpement this with _beginthreadex as I'm using
std::vector. Please provide some working code around the following details:
#include <windows.h> // for HANDLE
The last thing you want to include is windows.h, it pollutes the
namespace so much that it's not a good choice for an interface.
#include <process.h> // for _beginthreadex()
Try using a threading library for C++ it eliminates this code and will
work cross platform.
#include <vector>
using namespace std;
class A
{
private:
vector<double> v;
double d; // some other variable common to each thread;
double bar( double x );
public:
vector<double> foo();
};
vector<double> A::foo()
{
vector r( v.size() );
for( int i=0; i<int(v.size()); ++i )
r[i] = bar( v[i] );
return r;
}
double A::bar( double x )
{
double r = x*d; // some function using x and d
// obviosly more complicated in the real code...
return r;
}
Now what I'd like is for multiple instances of bar to run on my two
cores. ...
There will be only one instance of bar. I assume you mean multiple threads.
... Can you help me please?
There are a number of ways to do this. Probably the best way in this
case is to use OMP. This code below would parallelize on an OMP capable
compiler.
#include <omp.h>
....
vector<double> A::foo()
{
vector r( v.size() );
#pragma omp parallel for
for( int i=0; i<int(v.size()); ++i )
r[i] = bar( v[i] );
return r;
}
Threads get very complex very quickly. There is alot hidden under the
covers when you use OMP. If you're doing very complex stuff using
threads where there is alot of interaction, you can run into trouble if
you don't understand what OMP is doing for you.