473,554 Members | 2,919 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

What's the connection between objects and threads?

Hi

I have to write a multi-threaded program. I decided to take an OO
approach to it. I had the idea to wrap up all of the thread functions
in a mix-in class called Threadable. Then when an object should run
in its own thread, it should implement this mix-in class. Does this
sound like plausible design decision?

I'm surprised that C++ doesn't have such functionality, say in its
STL. This absence of a thread/object relationship in C++ leads me to
believe that my idea isn't a very good one.

I would appreciate your insights. thanks
Jun 27 '08 #1
167 8200
darren wrote:
Hi

I have to write a multi-threaded program. I decided to take an OO
approach to it. I had the idea to wrap up all of the thread functions
in a mix-in class called Threadable. Then when an object should run
in its own thread, it should implement this mix-in class. Does this
sound like plausible design decision?

I'm surprised that C++ doesn't have such functionality, say in its
STL. This absence of a thread/object relationship in C++ leads me to
believe that my idea isn't a very good one.
The next revision of the C++ standard does in fact have thread support.

The threading concepts in the next revision will probably work with what
you describe but there is a few newer concepts - one is called a "future".

In the meantime, there are some alternative libraries - boost implements
many of the standard's new features already as well as other like
commonc++ and Austria c++ also have cross platform threading support for
C++.

In most of my newer projects, I use thread pools which is very different
to threads.
Jun 27 '08 #2
darren <mi******@gmail .comwrote in news:7083eb1a-4dbd-4b94-866b-
fd**********@c1 9g2000prf.googl egroups.com:
Hi

I have to write a multi-threaded program. I decided to take an OO
approach to it. I had the idea to wrap up all of the thread functions
in a mix-in class called Threadable. Then when an object should run
in its own thread, it should implement this mix-in class. Does this
sound like plausible design decision?

I'm surprised that C++ doesn't have such functionality, say in its
STL. This absence of a thread/object relationship in C++ leads me to
believe that my idea isn't a very good one.

I would appreciate your insights. thanks
The current semi-official solution for threading in C++ is boost::thread
library. From what I've heard the C++0x standard will also be based on
that.

In boost::thread one has a functor object, which is copied over to the
started thread and then executed. Each functor object has its own thread
function. I see no point for any Threadable base class or "interface" .

In principle, no object does run in any thread. Only the objects' methods
might run in some thread or another, depending on which thread they are
called. There are at least two useful types of objects:

- single-threaded objects, whose methods may not run in parallel by
different threads. This is best ensured by that the pointer(s) to the
object are visible only to a single thread at a time; passing the object
to another thread is possible by ensuring there are no pointers left to
the object or its inners in the current owner thread.

- multi-threaded objects, whose all public methods can be called from any
thread at any time. Typically objects of this kind perform internal
locking when accessing their private data.

hth
Paavo

Jun 27 '08 #3
On May 17, 10:20*pm, darren <minof...@gmail .comwrote:

"What's the connection between objects and threads?"

Good question. In C++ there is no connection between objects and
threads since there are no threads in C++.

C++ does not have the notion of the process or the thread of
computation at the language level. On the other hand, C++ does have
the notion of the object at the language level. It is an object-
oriented programming language but not a concurrent object-oriented
one. The bad news is that it is not going to be one either.

The good news is that you can introduce threads of computation into a C
++ program via some libraries. The coming C++0x would even include
such a library, though.

So, you can take any concurrency libraries to mix threads into an
object-oriented program in C++. Objects and threads of computation are
usually orthogonal to each other. Objects are (passive) data
structures and, on the other hand, threads of computation are rather
activities with their own program counters in your program.

You can keep them separate as was done in the first class-based
concurrent programming language, Concurrent Pascal, or you can combine
them together as was done, for instance, in an early language proposal
called Distributed Processes (DP).
I had the idea to wrap up all of the thread functions
in a mix-in class called Threadable."
What do you mean by "thread functions"?
Does this
sound like plausible design decision?
It looks like you have the approach in mind where the objects are data
structures (passive elements) and the threads of computation (active
elements) are orthogonal to each other. In this case you could keep
them separate and do not intermix them, it would not be a good idea.
Although, if you must use any lower level library (such as Pthread),
it is a good idea to build your own higher level abstractions, I
think.

In this case it is very important to make a difference between the
objects which are meant to be used exclusively from one thread of
computation only and between the objects which are to be shared among
many threads. The shared objects must be protected so that they could
be accessed by the threads in a mutually exclusive way only (see the
Monitor concept).

Best Regards,
Szabolcs
Jun 27 '08 #4
Thanks for the responses everybody.

I have actually heard of Boost. I saw it in another post on this user
group about threads. My dilemma is that for this project, we were
specifically told that we must use the pthread library and our
deliverable must only be source code and a Makefile.

Doest Boost use pthread library calls in its implementation, or are
they up to something else? Maybe I'll email my prof and ask if using
Boost is permitted.

As for my current idea:

I planned to write a class called myThreads which would wrap up calls
to the pthread library, like pthread_create. Then anytime i need a
thread I'll instantiate one of these objects. I was thinking that in
one of these 'myThread" constructors, a new thread would be created
and ran. Again, i'm new to thread programming, so i dont know if this
will work or not.

there was also mention about threadpools. Our instructor said this may
be a good way to implement our project. How are they significantly
different than concepts of thread programming (as somebody here
mentioned they were).

thanks again.
Jun 27 '08 #5
"darren" <mi******@gmail .comwrote in message
news:3e******** *************** ***********@d19 g2000prm.google groups.com...
Thanks for the responses everybody.

I have actually heard of Boost. I saw it in another post on this user
group about threads. My dilemma is that for this project, we were
specifically told that we must use the pthread library and our
deliverable must only be source code and a Makefile.

Doest Boost use pthread library calls in its implementation, or are
they up to something else? Maybe I'll email my prof and ask if using
Boost is permitted.

As for my current idea:

I planned to write a class called myThreads which would wrap up calls
to the pthread library, like pthread_create. Then anytime i need a
thread I'll instantiate one of these objects. I was thinking that in
one of these 'myThread" constructors, a new thread would be created
and ran. Again, i'm new to thread programming, so i dont know if this
will work or not.
[...]

You don't generally want to create threads in constructors because of a
possible race-condition. Think of starting a thread in an object's
constructor which starts to run and operate on it _before_ its ctor has
finished... Anyway:

http://groups.google.com/group/comp....9b2ce54349af0f
(please read all!)


Here is some very simple source-code that might help you:
_______________ _______________ _______________ _______________ ________

/* VERY Simple Thread Library Code
_______________ _______________ _______________ _______________ __*/
#include <pthread.h>

class thread_base;
extern "C" void* thread_base_ent ry(void*);
static void thread_create(t hread_base* const);
static void thread_join(thr ead_base* const);

class thread_base {
pthread_t m_id;
friend void* thread_base_ent ry(void*);
friend void thread_create(t hread_base* const);
friend void thread_join(thr ead_base* const);
virtual void on_thread_entry () = 0;
public:
virtual ~thread_base() throw() = 0;
};
thread_base::~t hread_base() throw() {}

void* thread_base_ent ry(void* state) {
reinterpret_cas t<thread_base*> (state)->on_thread_entr y();
return 0;
}
void thread_create(t hread_base* const _this) {
int const status = pthread_create( &_this->m_id, NULL,
thread_base_ent ry, _this);
if (status) {
throw int(status);
}
}
void thread_join(thr ead_base* const _this) {
int const status = pthread_join(_t his->m_id, NULL);
if (status) {
throw int(status);
}
}
/* Very Simple Application Code
_______________ _______________ _______________ _______________ __*/
#include <cstdio>

class my_thread : public thread_base {
public:
my_thread() {
std::printf("(% p)-my_thread::my_t hread()\n",
reinterpret_cas t<void*>(this)) ;
}

~my_thread() throw() {
std::printf("(% p)-my_thread::~my_ thread() throw()\n",
reinterpret_cas t<void*>(this)) ;
}

private:
void on_thread_entry () {
std::printf("vo id (%p)-my_thread::on_t hread_entry()\n ",
reinterpret_cas t<void*>(this)) ;
}
};
#define RUN_DEPTH() 10
#define THREAD_DEPTH() 32
int main() {
int runs = 0;
for (; runs < RUN_DEPTH(); ++runs) {
int i = 0;
my_thread threads[THREAD_DEPTH()];

try {
for (; i < THREAD_DEPTH(); ++i) {
thread_create(& threads[i]);
}
} catch (int const& e) {
std::printf("th read_create throws status %d!\n", e);
}

for (--i; i -1; --i) {
try {
thread_join(&th reads[i]);
} catch (int const& e) {
std::printf("th read_join throws status %d!\n", e);
}
}
}

/*~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~ ~*/
std::puts("\n\n _______________ _______________ ______________\ n\
Press <ENTERto exit...");
std::getchar();
return 0;
}

_______________ _______________ _______________ _______________ ________

Any questions?

Jun 27 '08 #6
On May 17, 8:35 pm, "Chris Thomasson" <cris...@comcas t.netwrote:
"darren" <minof...@gmail .comwrote in message

news:3e******** *************** ***********@d19 g2000prm.google groups.com...
Thanks for the responses everybody.
I have actually heard of Boost. I saw it in another post on this user
group about threads. My dilemma is that for this project, we were
specifically told that we must use the pthread library and our
deliverable must only be source code and a Makefile.
Doest Boost use pthread library calls in its implementation, or are
they up to something else? Maybe I'll email my prof and ask if using
Boost is permitted.
As for my current idea:
I planned to write a class called myThreads which would wrap up calls
to the pthread library, like pthread_create. Then anytime i need a
thread I'll instantiate one of these objects. I was thinking that in
one of these 'myThread" constructors, a new thread would be created
and ran. Again, i'm new to thread programming, so i dont know if this
will work or not.

[...]

You don't generally want to create threads in constructors because of a
possible race-condition. Think of starting a thread in an object's
constructor which starts to run and operate on it _before_ its ctor has
finished... Anyway:

http://groups.google.com/group/comp..../browse_frm/th...
(please read all!)

Here is some very simple source-code that might help you:
_______________ _______________ _______________ _______________ ________

/* VERY Simple Thread Library Code
_______________ _______________ _______________ _______________ __*/
#include <pthread.h>

class thread_base;
extern "C" void* thread_base_ent ry(void*);
static void thread_create(t hread_base* const);
static void thread_join(thr ead_base* const);

class thread_base {
pthread_t m_id;
friend void* thread_base_ent ry(void*);
friend void thread_create(t hread_base* const);
friend void thread_join(thr ead_base* const);
virtual void on_thread_entry () = 0;
public:
virtual ~thread_base() throw() = 0;

};

thread_base::~t hread_base() throw() {}

void* thread_base_ent ry(void* state) {
reinterpret_cas t<thread_base*> (state)->on_thread_entr y();
return 0;

}

void thread_create(t hread_base* const _this) {
int const status = pthread_create( &_this->m_id, NULL,
thread_base_ent ry, _this);
if (status) {
throw int(status);
}

}

void thread_join(thr ead_base* const _this) {
int const status = pthread_join(_t his->m_id, NULL);
if (status) {
throw int(status);
}

}

/* Very Simple Application Code
_______________ _______________ _______________ _______________ __*/
#include <cstdio>

class my_thread : public thread_base {
public:
my_thread() {
std::printf("(% p)-my_thread::my_t hread()\n",
reinterpret_cas t<void*>(this)) ;
}

~my_thread() throw() {
std::printf("(% p)-my_thread::~my_ thread() throw()\n",
reinterpret_cas t<void*>(this)) ;
}

private:
void on_thread_entry () {
std::printf("vo id (%p)-my_thread::on_t hread_entry()\n ",
reinterpret_cas t<void*>(this)) ;
}

};

#define RUN_DEPTH() 10
#define THREAD_DEPTH() 32
int main() {
int runs = 0;
for (; runs < RUN_DEPTH(); ++runs) {
int i = 0;
my_thread threads[THREAD_DEPTH()];

try {
for (; i < THREAD_DEPTH(); ++i) {
thread_create(& threads[i]);
}
} catch (int const& e) {
std::printf("th read_create throws status %d!\n", e);
}

for (--i; i -1; --i) {
try {
thread_join(&th reads[i]);
} catch (int const& e) {
std::printf("th read_join throws status %d!\n", e);
}
}
}

/*~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~ ~*/
std::puts("\n\n _______________ _______________ ______________\ n\
Press <ENTERto exit...");
std::getchar();
return 0;

}

_______________ _______________ _______________ _______________ ________

Any questions?
hi Chris. Thanks for the reply and the sample code. I'll have to
spend some time understanding it. For starters why do you have this
ection:
class thread_base;
extern "C" void* thread_base_ent ry(void*);
static void thread_create(t hread_base* const);
static void thread_join(thr ead_base* const);
I've never seen code like this. are the parameters taking pointers to
a class??? it seems like thread_create is declared twoice, once as
friend and once not...

I've also never seen extern C before, i'll have to look up what that
is.

thanks again.
Jun 27 '08 #7
On May 18, 3:24 am, darren <minof...@gmail .comwrote:
Thanks for the responses everybody.

I have actually heard of Boost. I saw it in another post on this user
group about threads. My dilemma is that for this project, we were
specifically told that we must use the pthread library and our
deliverable must only be source code and a Makefile.

Doest Boost use pthread library calls in its implementation, or are
they up to something else? Maybe I'll email my prof and ask if using
Boost is permitted.

As for my current idea:

I planned to write a class called myThreads which would wrap up calls
to the pthread library, like pthread_create. Then anytime i need a
thread I'll instantiate one of these objects. I was thinking that in
one of these 'myThread" constructors, a new thread would be created
and ran. Again, i'm new to thread programming, so i dont know if this
will work or not.

there was also mention about threadpools. Our instructor said this may
be a good way to implement our project. How are they significantly
different than concepts of thread programming (as somebody here
mentioned they were).

thanks again.
At the company that I'm working we work the way you suggested
(which could be imply that YOU DONT WANT TO USE IT! ;) )
but it works fine and most of the times it's transparent.

My problem with thread pools (and I'll be happy if someone contradicts
me)
is that until .Net did'nt introduce thread pools I have'nt heared
about it
and it makes me worried that maybe it's a bit platform specific.
(But if you dont care than it's great method to ease your work)

If you could shed some light on your project maybe people could
give a more precise counsel on the MT method you should use...
Jun 27 '08 #8
On May 18, 12:43 pm, darren <minof...@gmail .comwrote:
A couple of things i'm thinking about:
1. As per the reason i created this post, I was thinking about how
objects related to threads. At first I was thinking that an object
should create a thread. this has been advised as bad (thanks for the
advice!). Now I'm thinking that instead, threads should create
objects, and destroy them before the thread ends. for example, when a
request is in the queue, a thread is created to handle it. Within this
new thread, a RequestHandler object is instantiated. It's methods are
used to process the request. The object is then destroyed. Finally,
the thread ends.

2 I was thinking about thread pools. Maybe there could be 10 threads
set up, waiting for requests. I dont know much about thread pools yet
though. It may not be appropriate. Or, maybe the threads could be
sleeping, then awoken by signaling when a request enters the queue.

1. sounds good maybe you would like to read about RAII
(or auto_ptr in stl - remeber not to create a continer of auto_ptrs!)

2. use thread pools. it's easy and it's a "fire and forget"
mechanizm...
Szabolcs Ferenczi wrote:
Try to avoid using singletons (if you refer to the singleton pattern).
It is not a good idea even in non-MT programs. You can always avoid
using singletons by disciplined programming. In this case you do not
need singleton either.
He is right but! The fact that "sigletons are evil" (google it) is not
always a common knowledge.
If you've learned singleton you are being expected to use it and
reciting to you prof\tester why you decided to avoid using singletons
will not always be accepted.
Jun 27 '08 #9
On May 18, 11:43*am, darren <minof...@gmail .comwrote:
5. if an entry is in there, a new thread is spawned to handle the
request. That thread then dies.
If you make the shared data structure thread safe so that multiple
threads can get element from it, you do not have to create and destroy
the thread but you can launch a certain number of worker threads that
compete to obtain a work packets from the queue. This is a simple
solution. If you want to tune it dynamically according to the work
load, a thread pool can be set up.

Best Regards,
Szabolcs
Jun 27 '08 #10

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

Similar topics

15
8262
by: Rob Nicholson | last post by:
I'm starting to worry a bit now. We're getting the above error when two users hit the same database/page on an ASP.NET application using ADO.NET, talking to a SQL 7 server. The error is perfectly repeatable :-( But this should help! The error is occurring inside ExecuteReader which uses a DataReader internally. Here are some things that...
7
2458
by: Lau Lei Cheong | last post by:
Hello, Actually I think I should have had asked it long before, but somehow I haven't. Here's the scenerio: Say we have a few pages in an ASP.NET project, each of them needs to connect to the database(Does not really matter but, in case you need to know, either MSSQL or ODBC ones) a few times when it loads to do the CURD things. How...
10
12361
by: nephish | last post by:
hey there, i have a huge app that connects to MySQL. There are three threads that are continually connecting and disconnecting to the db. The problem is, if there is an error, it faults out sometimes without closing the connection. i connect like this. db = MySQLdb.connect(host="localhost", user="MyUser", passwd="MyPassword", db="Stuff")...
10
3149
by: Steven Blair | last post by:
As I understand it, if I create a connection object in my application and close the connection, the next time I open a connection with the same connection string I should be using a pooled connection? Is this possible over different instances of a class. For example Instance 1 of my dll is alive and creates a connection to a Database....
0
7600
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main...
0
7521
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language...
0
7802
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. ...
0
8042
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that...
1
7563
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For...
1
5436
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 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 a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes...
0
5155
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert...
1
2020
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
1
1134
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.