473,722 Members | 2,240 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

a really simple C++ abstraction around pthread_t...

I use the following technique in all of my C++ projects; here is the example
code with error checking omitted for brevity:
_______________ _______________ _______________ _______________ _____
/* Simple Thread Object
_______________ _______________ _______________ _______________ __*/
#include <pthread.h>
extern "C" void* thread_entry(vo id*);

class thread_base {
pthread_t m_tid;
friend void* thread_entry(vo id*);
virtual void on_active() = 0;

public:
virtual ~thread_base() = 0;

void active_run() {
pthread_create( &m_tid, NULL, thread_entry, this);
}

void active_join() {
pthread_join(m_ tid, NULL);
}
};

thread_base::~t hread_base() {}

void* thread_entry(vo id* state) {
reinterpret_cas t<thread_base*> (state)->on_active();
return 0;
}

template<typena me T>
struct active : public T {
active() : T() {
this->active_run() ;
}

~active() {
this->active_join( );
}

template<typena me T_p1>
active(T_p1 p1) : T(p1) {
this->active_run() ;
}

template<typena me T_p1, typename T_p2>
active(T_p1 p1, T_p2 p2) : T(p1, p2) {
this->active_run() ;
}

// [and on and on for more params...]
};


/* Simple Usage Example
_______________ _______________ _______________ _______________ __*/
#include <string>
#include <cstdio>
class worker : public thread_base {
std::string const m_name;

void on_active() {
std::printf("(% p)->worker(%s)::on _thread_entry() \n",
(void*)this, m_name.c_str()) ;
}

public:
worker(std::str ing const& name)
: m_name(name) {
std::printf("(% p)->worker(%s)::my _thread()\n",
(void*)this, m_name.c_str()) ;
}

~worker() {
std::printf("(% p)->worker(%s)::~m y_thread()\n",
(void*)this, m_name.c_str()) ;
}
};
class another_worker : public thread_base {
unsigned const m_id;
std::string const m_name;

void on_active() {
std::printf("(% p)->my_thread(%u/%s)::on_thread_ entry()\n",
(void*)this, m_id, m_name.c_str()) ;
}

public:
another_worker( unsigned const id, std::string const& name)
: m_id(id), m_name(name) {
}
};
int main(void) {
{
active<workerwo rkers[] = {
"Chris",
"John",
"Jane",
"Steve",
"Richard",
"Lisa"
};

active<another_ workerother_wor kers[] = {
active<another_ worker>(21, "Larry"),
active<another_ worker>(87, "Paul"),
active<another_ worker>(43, "Peter"),
active<another_ worker>(12, "Shelly"),
};
}

std::puts("\n\n \n_____________ _____\nhit <ENTERto exit...");
std::fflush(std out);
std::getchar();
return 0;
}
_______________ _______________ _______________ _______________ _____


I personally like this technique better than Boost. I find it more straight
forward and perhaps more object oriented, the RAII nature of the `active'
helper class does not hurt either. Also, I really do think its more
"efficient" than Boost in the way it creates threads because it does not
copy anything...

IMHO, the really nice thing about it would have to be the `active' helper
class. It allows me to run and join any object from the ctor/dtor that
exposes a common interface of (T::active_run/join). Also, it allows me to
pass a variable number of arguments to the object it wraps directly through
its ctor; this is fairly convenient indeed...
Any suggestions on how I can improve this construct?

Oct 30 '08 #1
17 5813
On Oct 30, 10:39*pm, "Chris M. Thomasson" <n...@spam.inva lidwrote:
I use the following technique in all of my C++ projects; here is the example
code with error checking omitted for brevity:
_______________ _______________ _______________ _______________ _____
/* Simple Thread Object
_______________ _______________ _______________ _______________ __*/
#include <pthread.h>

extern "C" void* thread_entry(vo id*);

class thread_base {
* pthread_t m_tid;
* friend void* thread_entry(vo id*);
* virtual void on_active() = 0;

public:
* virtual ~thread_base() = 0;

* void active_run() {
* * pthread_create( &m_tid, NULL, thread_entry, this);
* }

* void active_join() {
* * pthread_join(m_ tid, NULL);
* }

};

thread_base::~t hread_base() {}

void* thread_entry(vo id* state) {
* reinterpret_cas t<thread_base*> (state)->on_active();
* return 0;

}

template<typena me T>
struct active : public T {
* active() : T() {
* * this->active_run() ;
* }

* ~active() {
* * this->active_join( );
* }

* template<typena me T_p1>
* active(T_p1 p1) : T(p1) {
* * this->active_run() ;
* }

* template<typena me T_p1, typename T_p2>
* active(T_p1 p1, T_p2 p2) : T(p1, p2) {
* * this->active_run() ;
* }

* // [and on and on for more params...]

};

/* Simple Usage Example
_______________ _______________ _______________ _______________ __*/
#include <string>
#include <cstdio>

class worker : public thread_base {
* std::string const m_name;

* void on_active() {
* * std::printf("(% p)->worker(%s)::on _thread_entry() \n",
* * * (void*)this, m_name.c_str()) ;
* }

public:
* worker(std::str ing const& name)
* * : m_name(name) {
* * std::printf("(% p)->worker(%s)::my _thread()\n",
* * * (void*)this, m_name.c_str()) ;
* }

* ~worker() {
* * std::printf("(% p)->worker(%s)::~m y_thread()\n",
* * *(void*)this, m_name.c_str()) ;
* }

};

class another_worker : public thread_base {
* unsigned const m_id;
* std::string const m_name;

* void on_active() {
* * std::printf("(% p)->my_thread(%u/%s)::on_thread_ entry()\n",
* * * (void*)this, m_id, m_name.c_str()) ;
* }

public:
* another_worker( unsigned const id, std::string const& name)
* * : m_id(id), m_name(name) {
* }

};

int main(void) {
* {
* * active<workerwo rkers[] = {
* * * "Chris",
* * * "John",
* * * "Jane",
* * * "Steve",
* * * "Richard",
* * * "Lisa"
* * };

* * active<another_ workerother_wor kers[] = {
* * * active<another_ worker>(21, "Larry"),
* * * active<another_ worker>(87, "Paul"),
* * * active<another_ worker>(43, "Peter"),
* * * active<another_ worker>(12, "Shelly"),
* * };
* }

* std::puts("\n\n \n_____________ _____\nhit <ENTERto exit...");
* std::fflush(std out);
* std::getchar();
* return 0;}

_______________ _______________ _______________ _______________ _____

I personally like this technique better than Boost. I find it more straight
forward and perhaps more object oriented, the RAII nature of the `active'
helper class does not hurt either. Also, I really do think its more
"efficient" than Boost in the way it creates threads because it does not
copy anything...

IMHO, the really nice thing about it would have to be the `active' helper
class. It allows me to run and join any object from the ctor/dtor that
exposes a common interface of (T::active_run/join). Also, it allows me to
pass a variable number of arguments to the object it wraps directly through
its ctor; this is fairly convenient indeed...

Any suggestions on how I can improve this construct?
Now it is better that you have taken the advice about the terminology
(active):

http://groups.google.com/group/comp....915b5211cce641

Best Regards,
Szabolcs
Oct 30 '08 #2

"Szabolcs Ferenczi" <sz************ ***@gmail.comwr ote in message
news:de******** *************** ***********@u29 g2000pro.google groups.com...
On Oct 30, 10:39 pm, "Chris M. Thomasson" <n...@spam.inva lidwrote:
I use the following technique in all of my C++ projects; here is the
example
code with error checking omitted for brevity:
_______________ _______________ _______________ _______________ _____
[...]
_______________ _______________ _______________ _______________ _____

I personally like this technique better than Boost. I find it more
straight
forward and perhaps more object oriented, the RAII nature of the
`active'
helper class does not hurt either. Also, I really do think its more
"efficient" than Boost in the way it creates threads because it does not
copy anything...

IMHO, the really nice thing about it would have to be the `active'
helper
class. It allows me to run and join any object from the ctor/dtor that
exposes a common interface of (T::active_run/join). Also, it allows me
to
pass a variable number of arguments to the object it wraps directly
through
its ctor; this is fairly convenient indeed...

Any suggestions on how I can improve this construct?
Now it is better that you have taken the advice about the terminology
(active):
http://groups.google.com/group/comp....915b5211cce641
Yeah; I think your right.

Oct 30 '08 #3

"Chris M. Thomasson" <no@spam.invali dwrote in message
news:dI******** ****@newsfe01.i ad...
>I use the following technique in all of my C++ projects; here is the
example code with error checking omitted for brevity:
_______________ _______________ _______________ _______________ _____
[...]
_______________ _______________ _______________ _______________ _____
[...]
Any suggestions on how I can improve this construct?
One addition I forgot to add would be creating an explict `guard' helper
object within the `active' helper object so that one can create objects and
intervene between its ctor and when it actually gets ran... Here is full
example code showing this moment:
_______________ _______________ _______________ _______________ _____
/* Simple Thread Object
_______________ _______________ _______________ _______________ __*/
#include <pthread.h>
extern "C" void* thread_entry(vo id*);

class thread_base {
pthread_t m_tid;
friend void* thread_entry(vo id*);
virtual void on_active() = 0;

public:
virtual ~thread_base() = 0;

void active_run() {
pthread_create( &m_tid, NULL, thread_entry, this);
}

void active_join() {
pthread_join(m_ tid, NULL);
}
};

thread_base::~t hread_base() {}

void* thread_entry(vo id* state) {
reinterpret_cas t<thread_base*> (state)->on_active();
return 0;
}
template<typena me T>
struct active : public T {
struct guard {
T& m_object;

guard(T& object) : m_object(object ) {
m_object.active _run();
}

~guard() {
m_object.active _join();
}
};

active() : T() {
this->active_run() ;
}

~active() {
this->active_join( );
}

template<typena me T_p1>
active(T_p1 p1) : T(p1) {
this->active_run() ;
}

template<typena me T_p1, typename T_p2>
active(T_p1 p1, T_p2 p2) : T(p1, p2) {
this->active_run() ;
}

// [and on and on for more params...]
};


/* Simple Usage Example
_______________ _______________ _______________ _______________ __*/
#include <string>
#include <cstdio>
class worker : public thread_base {
std::string const m_name;

void on_active() {
std::printf("(% p)->worker(%s)::on _active()\n",
(void*)this, m_name.c_str()) ;
}

public:
worker(std::str ing const& name)
: m_name(name) {
std::printf("(% p)->worker(%s)::my _thread()\n",
(void*)this, m_name.c_str()) ;
}

~worker() {
std::printf("(% p)->worker(%s)::~m y_thread()\n",
(void*)this, m_name.c_str()) ;
}
};
class another_worker : public thread_base {
unsigned const m_id;
std::string const m_name;

void on_active() {
std::printf("(% p)->another_worker (%u/%s)::on_active( )\n",
(void*)this, m_id, m_name.c_str()) ;
}

public:
another_worker( unsigned const id, std::string const& name)
: m_id(id), m_name(name) {
}
};
int main(void) {
{
worker w1("Amy");
worker w2("Kim");
worker w3("Chris");
another_worker aw1(123, "Kelly");
another_worker aw2(12345, "Tim");
another_worker aw3(87676, "John");

active<thread_b ase>::guard w12_aw12[] = {
w1, w2, w3,
aw1, aw2, aw3
};

active<workerwo rkers[] = {
"Jim",
"Dave",
"Regis"
};

active<another_ workerother_wor kers[] = {
active<another_ worker>(999, "Jane"),
active<another_ worker>(888, "Ben"),
active<another_ worker>(777, "Larry")
};
}

std::puts("\n\n \n_____________ _____\nhit <ENTERto exit...");
std::fflush(std out);
std::getchar();
return 0;
}
_______________ _______________ _______________ _______________ _____


Take notice of the following code snippet residing within main:
worker w1("Amy");
worker w2("Kim");
worker w3("Chris");
another_worker aw1(123, "Kelly");
another_worker aw2(12345, "Tim");
another_worker aw3(87676, "John");

active<thread_b ase>::guard w12_aw12[] = {
w1, w2, w3,
aw1, aw2, aw3
};
This shows how one can make use of the guard object. The objects are fully
constructed, and they allow you do go ahead and do whatever you need to do
with them _before_ you actually run/join them. This can be a very convenient
ability.

Oct 30 '08 #4
"Chris M. Thomasson" wrote
"Chris M. Thomasson" wrote
I use the following technique in all of my C++ projects; here is the
example code with error checking omitted for brevity:

[...]
Any suggestions on how I can improve this construct?

One addition I forgot to add would be creating an explict `guard' helper
object within the `active' helper object so that one can create objects and
intervene between its ctor and when it actually gets ran... Here is full
example code showing this moment:
_______________ _______________ _______________ _______________ _____
/* Simple Thread Object
_______________ _______________ _______________ _______________ __*/
#include <pthread.h>
extern "C" void* thread_entry(vo id*);

class thread_base {
pthread_t m_tid;
friend void* thread_entry(vo id*);
virtual void on_active() = 0;

public:
virtual ~thread_base() = 0;

void active_run() {
pthread_create( &m_tid, NULL, thread_entry, this);
}

void active_join() {
pthread_join(m_ tid, NULL);
}
};

thread_base::~t hread_base() {}

void* thread_entry(vo id* state) {
reinterpret_cas t<thread_base*> (state)->on_active();
return 0;
}
template<typena me T>
struct active : public T {
struct guard {
T& m_object;

guard(T& object) : m_object(object ) {
m_object.active _run();
}

~guard() {
m_object.active _join();
}
};

active() : T() {
this->active_run() ;
}
<snip>

Hmm. is it ok to stay within the ctor for the whole
duration of the lifetime of the object?
IMO the ctor should be used only for initializing the object,
but not for executing or calling the "main loop" of the object
because the object is fully created only after the ctor has finished,
isn't it?

Oct 31 '08 #5
"Adem" <fo***********@ alicewho.comwro te in message
news:ge******** **@aioe.org...
"Chris M. Thomasson" wrote
[...]
>template<typen ame T>
struct active : public T {
struct guard {
T& m_object;

guard(T& object) : m_object(object ) {
m_object.active _run();
}

~guard() {
m_object.active _join();
}
};

active() : T() {

// at this point, T is constructed.

> this->active_run() ;

// the procedure above only concerns T.
> }
<snip>

Hmm. is it ok to stay within the ctor for the whole
duration of the lifetime of the object?
In this case it is because the object `T' is fully constructed before its
`active_run' procedure is invoked.

IMO the ctor should be used only for initializing the object,
but not for executing or calling the "main loop" of the object
because the object is fully created only after the ctor has finished,
isn't it?
Normally your correct. However, the `active' object has nothing to do with
the "main loop" of the object it wraps. See following discussion for further
context:

http://groups.google.com/group/comp....cae1851bb5f215

The OP of that thread was trying to start the thread within the ctor of the
threading base-class. This invokes a race-condition such that the derived
class can be called without its ctor being completed. The `active' helper
template gets around that by automating the calls to `active_run/join' on a
completely formed object T.

Oct 31 '08 #6
On Oct 31, 3:40*pm, "Adem" <for-usenet...@alice who.comwrote:
"Chris M. Thomasson" wrote
"Chris M. Thomasson" wrote
>I use the following technique in all of my C++ projects; here is the
>example code with error checking omitted for brevity:
[...]
Any suggestions on how I can improve this construct?
One addition I forgot to add would be creating an explict `guard' helper
object within the `active' helper object so that one can create objectsand
intervene between its ctor and when it actually gets ran... Here is full
example code showing this moment:
_______________ _______________ _______________ _______________ _____
/* Simple Thread Object
_______________ _______________ _______________ _______________ __*/
#include <pthread.h>
extern "C" void* thread_entry(vo id*);
class thread_base {
* pthread_t m_tid;
* friend void* thread_entry(vo id*);
* virtual void on_active() = 0;
public:
* virtual ~thread_base() = 0;
* void active_run() {
* * pthread_create( &m_tid, NULL, thread_entry, this);
* }
* void active_join() {
* * pthread_join(m_ tid, NULL);
* }
};
thread_base::~t hread_base() {}
void* thread_entry(vo id* state) {
* reinterpret_cas t<thread_base*> (state)->on_active();
* return 0;
}
template<typena me T>
struct active : public T {
* struct guard {
* * T& m_object;
* * guard(T& object) : m_object(object ) {
* * * m_object.active _run();
* * }
* * ~guard() {
* * * m_object.active _join();
* * }
* };
* active() : T() {
* * this->active_run() ;
* }

<snip>
--
Hmm. is it ok to stay within the ctor for the whole
duration of the lifetime of the object?
It does not stay within the constructor since the constructor
completes after starting a thread.
IMO the ctor should be used only for initializing the object,
That is what is happening. Part of the initialisation is launching a
thread.
but not for executing or calling the "main loop" of the object
The C++ model allows any method calls from the constructor.

12.6.2.9
"Member functions (including virtual member functions, 10.3) can be
called for an object under construction."
http://www.open-std.org/jtc1/sc22/wg...2008/n2798.pdf
because the object is fully created only after the ctor has finished,
isn't it?
Yes, it is. In this case the object is fully constructed since the
thread is started in the wrapper after the object has been fully
constructed.

If you are interested in the arguments and counter arguments, you can
check the discussion thread where this construction has emerged:

"What's the connection between objects and threads?"
http://groups.google.com/group/comp....cae1851bb5f215

Best Regards,
Szabolcs
Oct 31 '08 #7
On Oct 30, 10:39*pm, "Chris M. Thomasson" <n...@spam.inva lidwrote:
Any suggestions on how I can improve this construct?
I think this construction is good enough for the moment. Now we should
turn to enhancing the communication part for shared objects in C++0x.

You know that Boost provides the scoped lock which has some advantage
over the explicit lock/unlock in Pthreads.

Furthermore, C++0x includes already some higher level wrapper
construct for making the wait for condition variables more natural or
user friendly. I refer to the wait wrapper, which expects the
predicate:

<quote>
template <class Predicate>
void wait(unique_loc k<mutex>& lock, Predicate pred);
Effects:
As if:
while (!pred())
wait(lock);
</quote>
http://www.open-std.org/jtc1/sc22/wg...008/n2497.html
</quote>

Actually, this wrapper could be combined with the scoped lock to get a
very high level construction in C++0x.

Well, ideally if they would dear to introduce some keywords in C++0x,
a bounded buffer could be expressed something like this.

template< typename T >
monitor class BoundedBuffer {
const unsigned int m_max;
std::deque<Tb;
public:
BoundedBuffer(c onst int n) : m_max(n) {}
void put(const T n) {
when (b.size() < m_max) {
b.push_back(n);
}
}
T get() {
T aux;
when (!b.empty()) {
aux = b.front();
b.pop_front();
}
return aux;
}
}

However, neither the `monitor' nor the `when' is not going to be
introduced in C++0x. The `when' would have the semantics of the
Conditional Critical Region.

Actually, something similar could be achieved with higher level
wrapper constructions that would result in program fragments like this
(I am not sure about the syntax, I did a simple transformation there):

template< typename T >
class BoundedBuffer : public Monitor {
const unsigned int m_max;
std::deque<Tb;
public:
BoundedBuffer(c onst int n) : m_max(n) {}
void put(const T n) {
{ When guard(b.size() < m_max);
b.push_back(n);
}
}
T get() {
T aux;
{ When guard(!b.empty( ));
aux = b.front();
b.pop_front();
}
return aux;
}
}

Here the super class would contain the necessary harness (mutex,
condvar) and the RAII object named `guard' could be similar to the
Boost scoped lock, it would provide locking and unlocking but in
addition it would wait in the constructor until the predicate is
satisfied. Something like this:

class When {
....
public:
When(...) {
// lock
// cv.wait(&lock, pred);
}
~When() {
// cv.broadcast
// unlock
}
};

The question is how would you hack the classes `Monitor' and `When' so
that active objects could be combined with this kind of monitor data
structure to complete the canonical example of producers-consumers.
Forget about efficiency concerns for now.

Best Regards,
Szabolcs
Oct 31 '08 #8

"Szabolcs Ferenczi" <sz************ ***@gmail.comwr ote in message
news:83******** *************** ***********@o4g 2000pra.googleg roups.com...
On Oct 30, 10:39 pm, "Chris M. Thomasson" <n...@spam.inva lidwrote:
Any suggestions on how I can improve this construct?
I think this construction is good enough for the moment. Now we should
turn to enhancing the communication part for shared objects in C++0x.
Okay.

[...]

The question is how would you hack the classes `Monitor' and `When' so
that active objects could be combined with this kind of monitor data
structure to complete the canonical example of producers-consumers.
Forget about efficiency concerns for now.
Here is a heck of a hack, in the form of a fully working program, for you
take a look at Szabolcs:
_______________ _______________ _______________ _______________ ___________
/* Simple Thread Object
_______________ _______________ _______________ _______________ __*/
#include <pthread.h>
extern "C" void* thread_entry(vo id*);

class thread_base {
pthread_t m_tid;
friend void* thread_entry(vo id*);
virtual void on_active() = 0;

public:
virtual ~thread_base() = 0;

void active_run() {
pthread_create( &m_tid, NULL, thread_entry, this);
}

void active_join() {
pthread_join(m_ tid, NULL);
}
};

thread_base::~t hread_base() {}

void* thread_entry(vo id* state) {
reinterpret_cas t<thread_base*> (state)->on_active();
return 0;
}
template<typena me T>
struct active : public T {
struct guard {
T& m_object;

guard(T& object) : m_object(object ) {
m_object.active _run();
}

~guard() {
m_object.active _join();
}
};

active() : T() {
this->active_run() ;
}

~active() {
this->active_join( );
}

template<typena me T_p1>
active(T_p1 p1) : T(p1) {
this->active_run() ;
}

template<typena me T_p1, typename T_p2>
active(T_p1 p1, T_p2 p2) : T(p1, p2) {
this->active_run() ;
}

// [and on and on for more params...]
};
/* Simple Moniter
_______________ _______________ _______________ _______________ __*/
class moniter {
pthread_mutex_t m_mutex;
pthread_cond_t m_cond;

public:
moniter() {
pthread_mutex_i nit(&m_mutex, NULL);
pthread_cond_in it(&m_cond, NULL);
}

~moniter() {
pthread_cond_de stroy(&m_cond);
pthread_mutex_d estroy(&m_mutex );
}

struct lock_guard {
moniter& m_moniter;

lock_guard(moni ter& moniter_) : m_moniter(monit er_) {
m_moniter.lock( );
}

~lock_guard() {
m_moniter.unloc k();
}
};

void lock() {
pthread_mutex_l ock(&m_mutex);
}

void unlock() {
pthread_mutex_u nlock(&m_mutex) ;
}

void wait() {
pthread_cond_wa it(&m_cond, &m_mutex);
}

void signal() {
pthread_cond_si gnal(&m_cond);
}

void broadcast() {
pthread_cond_si gnal(&m_cond);
}
};
#define when_x(mp_pred, mp_line) \
lock_guard guard_##mp_line (*this); \
while (! (mp_pred)) this->wait();

#define when(mp_pred) when_x(mp_pred, __LINE__)




/* Simple Usage Example
_______________ _______________ _______________ _______________ __*/
#include <cstdio>
#include <deque>
#define PRODUCE 10000
#define BOUND 100
#define YIELD 2
template<typena me T>
struct bounded_buffer : public moniter {
unsigned const m_max;
std::deque<Tm_b uffer;

public:
bounded_buffer( unsigned const max_) : m_max(max_) {}

void push(T const& obj) {
when (m_buffer.size( ) < m_max) {
m_buffer.push_b ack(obj);
signal();
}
}

T pop() {
T obj;
when (! m_buffer.empty( )) {
obj = m_buffer.front( );
m_buffer.pop_fr ont();
}
return obj;
}
};
class producer : public thread_base {
bounded_buffer< unsigned>& m_buffer;

void on_active() {
for (unsigned i = 0; i < PRODUCE; ++i) {
m_buffer.push(i + 1);
std::printf("pr oduced %u\n", i + 1);
if (! (i % YIELD)) { sched_yield(); }
}
}

public:
producer(bounde d_buffer<unsign ed>* buffer) : m_buffer(*buffe r) {}
};
struct consumer : public thread_base {
bounded_buffer< unsigned>& m_buffer;

void on_active() {
unsigned i;
do {
i = m_buffer.pop();
std::printf("co nsumed %u\n", i);
if (! (i % YIELD)) { sched_yield(); }
} while (i != PRODUCE);
}

public:
consumer(bounde d_buffer<unsign ed>* buffer) : m_buffer(*buffe r) {}
};


int main(void) {
{
bounded_buffer< unsignedb(BOUND );
active<producer p(&b);
active<consumer c(&b);
}

std::puts("\n\n \n_____________ _____\nhit <ENTERto exit...");
std::fflush(std out);
std::getchar();
return 0;
}
_______________ _______________ _______________ _______________ ___________



Please take notice of the following class, which compiles fine:
template<typena me T>
struct bounded_buffer : public moniter {
unsigned const m_max;
std::deque<Tm_b uffer;

public:
bounded_buffer( unsigned const max_) : m_max(max_) {}

void push(T const& obj) {
when (m_buffer.size( ) < m_max) {
m_buffer.push_b ack(obj);
signal();
}
}

T pop() {
T obj;
when (! m_buffer.empty( )) {
obj = m_buffer.front( );
m_buffer.pop_fr ont();
}
return obj;
}
};


Well, is that kind of what you had in mind? I make this possible by hacking
the following macro together:
#define when_x(mp_pred, mp_line) \
lock_guard guard_##mp_line (*this); \
while (! (mp_pred)) this->wait();

#define when(mp_pred) when_x(mp_pred, __LINE__)


It works, but its a heck of a hack! ;^D

Anyway, what do you think of this approach? I add my own "keyword".. . lol.

Oct 31 '08 #9
of course I have created a possible DEADLOCK condition! I totally forgot to
have the bounded_buffer signal/broadcast after it pops something! Here is
the FIXED version:


/* Simple Thread Object
_______________ _______________ _______________ _______________ __*/
#include <pthread.h>
extern "C" void* thread_entry(vo id*);

class thread_base {
pthread_t m_tid;
friend void* thread_entry(vo id*);
virtual void on_active() = 0;

public:
virtual ~thread_base() = 0;

void active_run() {
pthread_create( &m_tid, NULL, thread_entry, this);
}

void active_join() {
pthread_join(m_ tid, NULL);
}
};

thread_base::~t hread_base() {}

void* thread_entry(vo id* state) {
reinterpret_cas t<thread_base*> (state)->on_active();
return 0;
}
template<typena me T>
struct active : public T {
struct guard {
T& m_object;

guard(T& object) : m_object(object ) {
m_object.active _run();
}

~guard() {
m_object.active _join();
}
};

active() : T() {
this->active_run() ;
}

~active() {
this->active_join( );
}

template<typena me T_p1>
active(T_p1 p1) : T(p1) {
this->active_run() ;
}

template<typena me T_p1, typename T_p2>
active(T_p1 p1, T_p2 p2) : T(p1, p2) {
this->active_run() ;
}

// [and on and on for more params...]
};
/* Simple Moniter
_______________ _______________ _______________ _______________ __*/
class moniter {
pthread_mutex_t m_mutex;
pthread_cond_t m_cond;

public:
moniter() {
pthread_mutex_i nit(&m_mutex, NULL);
pthread_cond_in it(&m_cond, NULL);
}

~moniter() {
pthread_cond_de stroy(&m_cond);
pthread_mutex_d estroy(&m_mutex );
}

struct lock_guard {
moniter& m_moniter;

lock_guard(moni ter& moniter_) : m_moniter(monit er_) {
m_moniter.lock( );
}

~lock_guard() {
m_moniter.unloc k();
}
};

void lock() {
pthread_mutex_l ock(&m_mutex);
}

void unlock() {
pthread_mutex_u nlock(&m_mutex) ;
}

void wait() {
pthread_cond_wa it(&m_cond, &m_mutex);
}

void signal() {
pthread_cond_si gnal(&m_cond);
}

void broadcast() {
pthread_cond_si gnal(&m_cond);
}
};
#define when_x(mp_pred, mp_line) \
lock_guard guard_##mp_line (*this); \
while (! (mp_pred)) this->wait();

#define when(mp_pred) when_x(mp_pred, __LINE__)




/* Simple Usage Example
_______________ _______________ _______________ _______________ __*/
#include <cstdio>
#include <deque>
#define PRODUCE 10000
#define BOUND 100
#define YIELD 2
template<typena me T>
struct bounded_buffer : public moniter {
unsigned const m_max;
std::deque<Tm_b uffer;

public:
bounded_buffer( unsigned const max_) : m_max(max_) {}

void push(T const& obj) {
when (m_buffer.size( ) < m_max) {
m_buffer.push_b ack(obj);
broadcast();
}
}

T pop() {
T obj;
when (! m_buffer.empty( )) {
obj = m_buffer.front( );
m_buffer.pop_fr ont();
broadcast();
}
return obj;
}
};
class producer : public thread_base {
bounded_buffer< unsigned>& m_buffer;

void on_active() {
for (unsigned i = 0; i < PRODUCE; ++i) {
m_buffer.push(i + 1);
std::printf("pr oduced %u\n", i + 1);
if (! (i % YIELD)) { sched_yield(); }
}
}

public:
producer(bounde d_buffer<unsign ed>* buffer) : m_buffer(*buffe r) {}
};
struct consumer : public thread_base {
bounded_buffer< unsigned>& m_buffer;

void on_active() {
unsigned i;
do {
i = m_buffer.pop();
std::printf("co nsumed %u\n", i);
if (! (i % YIELD)) { sched_yield(); }
} while (i != PRODUCE);
}

public:
consumer(bounde d_buffer<unsign ed>* buffer) : m_buffer(*buffe r) {}
};


int main(void) {
{
bounded_buffer< unsignedb(BOUND );
active<producer p(&b);
active<consumer c(&b);
}

std::puts("\n\n \n_____________ _____\nhit <ENTERto exit...");
std::fflush(std out);
std::getchar();
return 0;
}


I am VERY sorry for this boneheaded mistake!!! OUCH!!!! BTW, the reason I
broadcast is so the bounded_buffer class can be used by multiple producers
and consumers.

Oct 31 '08 #10

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

Similar topics

4
1227
by: Dave Benjamin | last post by:
The recent conversation on prototype-based OOP and the Prothon project has been interesting. I've been playing around with the idea for awhile now, actually, since I do a lot of programming in JavaScript/ActionScript. I feel like people are focusing too much on the "prototype chain", which to me is mainly an attempt at reintroducing inheritance. I almost never use inheritance anymore, preferring delegation instead in most cases. What I...
26
1805
by: DeMarcus | last post by:
Let's say we're gonna make a system library and have a class with two prerequisites. * It will be used _a_lot_, and therefore need to be really efficient. * It can have two different implementations. (e.g. Unix/Windows) I feel stuck. The only solution I've seen so far is using the design pattern 'abstract factory' that gives me a pointer to a pure virtual interface (which can have whatever implementation). But that forces me to make a...
10
2373
by: serge calderara | last post by:
Dear all, I need to build a web application which will contains articles (long or short) I was wondering on what is the correct way to retrive those article on web page. In orther words, when there is such information to be displayed are they coming from imported files, database ? Where and how this type of information is stored ? What is the way to retrieve such information in order to display it in page ?
1
2330
by: DartmanX | last post by:
I'm looking for any comparisons of PHP Database Abstraction Layers out there, with an eye towards speed/efficiency. I'm still using PEAR::DB, which obviously leaves something to be desired. I'm at a point now where I can look at switching to a better system. Jason
25
2560
by: Colin McKinnon | last post by:
Hi all, There's lots of DB abstraction layers out there, but a quick look around them hasn't turned up anything which seems to met my requirements. Before I go off and write one I thought I'd ask here if anyone knows of such a beast... I want some code where I present an array of data, and the corresponding primary key and let the code work out whether to INSERT or UPDATE it, I also want to be able to present the data from a QBF or...
3
5095
by: S. Lorétan | last post by:
Hi guys, I'm coding an application connected to a database. I have some clients that use this program with 2 or 3 computers, and I use MsSQL Express for them. But if the client needs more computers to be connected to the database, I have to use a standard MsSQL. No problem with that, but I want to be able to switch from a database provider to another in an easy way. I know that this way to do is called "Data(base) abstraction layer",...
1
1673
by: rickycornell | last post by:
Greetings All, On past projects in PHP4 I had always just written my own libraries to deal with database interaction. Somehow I was operating in the dark that there were all these database abstraction things available that made my work on the libraries I made from scratch a waste of time. So now I've started researching all these things that are available, and I have to say I am a little confused. It's a matter of understanding the...
3
1903
by: TamusJRoyce | last post by:
Hello. This is my first thread here. My problem has probably been came across by a lot of people, but tutorials and things I've seen don't address it (usually too basic). My problem is that I would like to use Abstraction for a "plug-in" like interface to classes. class ThreadHandle { /* stuff here not yet dealing with threads */
6
9368
by: pythoNewbie | last post by:
Dear experts, I am trying to understand a simple semaphore program written in C, and trying to insert some printf statements in the code , but there is no output at all. #include<stdio.h> #include<phtread.h> #include<sys/ipc.h> #include<sys/sem.h>
0
8863
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 usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9384
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. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
9088
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8052
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6681
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 instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5995
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 into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4762
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3207
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
3
2147
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.