473,385 Members | 1,356 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,385 software developers and data experts.

multithreaded c++ question

I'm using VS.net 7.1 on Windows XP.

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
#include <process.h // for _beginthreadex()
#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<doubleA::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. Can you help me please?
Apr 10 '07 #1
3 1979
Hi,
Here is an implementation of my multithreading class (meant to derive from
it and overide run method)

unsigned int __stdcall CPProcess::Spawn(CPProcess *Self)
{
Self->Run();

return 0;
}

bool CPProcess::Start()
{
unsigned int ID = 0;

if( StopEvent = CreateEvent( 0, TRUE, FALSE, 0 ) )
{
if( !( ThreadID = reinterpret_cast<HANDLE>( _beginthreadex( 0, 0,
reinterpret_cast<unsigned int (__stdcall *)(void *)>( Spawn ), this, 0,
&ID) ) ) )
{
CloseHandle( StopEvent );
StopEvent = 0;
}
}

return ThreadID != 0;
}

void CPProcess::Stop()
{
SetEvent( StopEvent );

}

bool CPProcess::Wait(ULONG MilliSeconds)
{
if( WaitForSingleObject( ThreadID, MilliSeconds ) == WAIT_OBJECT_0 )
{
CloseHandle( StopEvent );
CloseHandle( ThreadID );
ThreadID = StopEvent = 0;
}

return ThreadID == 0;

}

bool CPProcess::Stopped()
{
return WaitForSingleObject( StopEvent, 0 ) == WAIT_OBJECT_0;
}

void CPProcess::Run()
{
}

Regards, Ron AF Greve

http://www.InformationSuperHighway.eu

"Chris Roth" <cz****@mail.usask.cawrote in message
news:ev**********@webmail.usask.ca...
I'm using VS.net 7.1 on Windows XP.

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
#include <process.h // for _beginthreadex()
#include <vector>

using namespace std;

class A
{
private:
vector<doublev;
double d; // some other variable common to each thread;
double bar( double x );
public:
vector<doublefoo();
};

vector<doubleA::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.
Can you help me please?

Apr 10 '07 #2
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<doubleA::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<doubleA::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.
Apr 10 '07 #3
On Apr 10, 8:57 pm, Chris Roth <czr...@mail.usask.cawrote:
I'm using VS.net 7.1 on Windows XP.
I'm more familiar with Posix threads, but I think the basic
principles are similar.
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.
What is _beginthreadex, and what is its relationship to
std::vector?
Please provide some working code around the following details:
#include <windows.h // for HANDLE
#include <process.h // for _beginthreadex()
#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<doubleA::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. Can you help me please?
The first, and most important question, is: does bar modify d in
your actual code? If so, you'll need a lock around each access
to d, which is likely to make the threaded code much, much
slower. Similar considerations apply if you modify the topology
(size or capacity) of any shared vector.

Secondly, what is the size of the vector, and how often is foo()
called. Creating a thread is expensive; if foo() is called a
lot, you'll want to use a pool of threads, so you don't have to
create new threads each time foo is called, especially if the
vectors aren't that big.

Finally: I'd define a few helper objects (maybe just structs) to
define what each thread should do. Maybe something along the
lines of:

struct ThreadData
{
A* object ;
vector< double >* result ;
int first ;
int last ;
ThreadIdType id ;

ThreadData( A* owner, vector<double>*r )
: object( owner )
, result( r )
{
}
} ;

with an overloaded foo:

void
A::foo( ThreadData const& data )
{
for ( int i = data.first ; i < data.last ; ++ i ) {
(*result)[ i ] = bar( v[ i ] ) ;
}
}

If you're starting the thread in foo, you'll need an `extern
"C"' function (or maybe some special Windows linkage) to kick
things off:

extern "C"
void* // or whatever Windows requires...
threadStarter( void* param )
{
ThreadData* data( static_cast< ThreadData* >( param ) ) ;
data->object->foo( *data ) ;
return NULL ; // or whatever...
}

Given this, foo becomes:

vector< double >
A::foo()
{
vector< double r( v.size() ) ;
static int const threadCount = numberOfCores ;
size_t perThread = v.size() / threadCount ;
size_t extras = v.size() % threadCount ;
size_t currentIndex = 0 ;
std::vector< ThreadData >
threads( threadCount,
ThreadData( this, &r ) ) ;
for ( size_t i = 0 ; i < threadCount ; ++ i ) {
threads[ i ].first = currentIndex ;
currentIndex += perThread ;
if ( extras != 0 ) {
++ currentIndex ;
-- extras ;
}
threads[ i ].last = currentIndex ;
StartThread( &threads[ i ].id, threadStarter,
&threads[ i ] ) ;
}
for ( size_t i = 0 ; i < threadCount ; ++ i ) {
JoinThread( &threads[ i ].id ) ;
}
}

Obviously, you'll have to use whatever the Windows API requires
for StartThread and JoinThread (CreateThread and
WaitForSingleObject, I think). And you really should add some
error handling as well. (Be very careful about leaving the
function once you've started some threads. Those threads are
using a local variable in the function, and will continue using
even if you leave the function. In case of error, you must
somehow cause all already started threads to stop, and then join
with them.)

--
James Kanze (GABI Software) email:ja*********@gmail.com
Conseils en informatique orientée objet/
Beratung in objektorientierter Datenverarbeitung
9 place Sémard, 78210 St.-Cyr-l'École, France, +33 (0)1 30 23 00 34

Apr 11 '07 #4

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

1
by: Google Mike | last post by:
I want to prepare some training for some new employees regarding the topic of multithreaded socket services implemented in PHP. I've been able to implement this with my own design, but I'd like to...
1
by: Elbert Lev | last post by:
I started with Python two weeks ago and already saved some time and efforts while writing 2 programs: 1. database extraction and backup tool, which runs once a month and creates a snapshot of...
2
by: pradyumna | last post by:
In Project settins - C/C++ - Code Generation, what is the difference between the option "Multithreaded" and "Multithreaded DLL". I understand that on selecting multithreaded option, single and...
6
by: Dan Kelley | last post by:
We have a multithreaded app that responds to events, and writes these events to a text file. This text file is used by an external system for further processing. We want to be able to write...
1
by: ravinder | last post by:
I wanted to develop a multithreaded program using OO concepts on windows platform. Problem: I have to simulate two layers(similar to TCP/IP stack layers), and the layer functionality is of finite...
3
by: Development | last post by:
I am creating 10 threads that do ecatly the same thing. I am having a very hard time debugging this scenario. It seems that by default when you are doing f10 or f11 all threads execute. You can...
9
by: nicolas.michel.lava | last post by:
Hi there, I have some trouble using STL containers. I'm working on a multithreaded (pthread) application making heavy usage of STL containers. All accesses to containers are made in locked...
3
by: groups | last post by:
Hi all, I've recently ported a rather large C application to run multithreaded. A few functions have seriously deteriorated in performance, in particular when accessing a rather large global...
3
by: | last post by:
Is it possible to have just a multithreaded sub procedure? What I need is a timer time_elapsed event (2 sec interval) send params to a sub that is multithreaded. I have a COM component used to...
3
by: Jake K | last post by:
I have a multithreaded application that I now want to convert into a Windows Service. Does application.run work in a windows service? Are there things to take into consideration when creating a...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome former...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.