[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.c++

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

Chris M. Thomasson

10/30/2008 9:39:00 PM

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(void*);

class thread_base {
pthread_t m_tid;
friend void* thread_entry(void*);
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::~thread_base() {}

void* thread_entry(void* state) {
reinterpret_cast<thread_base*>(state)->on_active();
return 0;
}

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

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

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

template<typename 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::string 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)::~my_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<worker> workers[] = {
"Chris",
"John",
"Jane",
"Steve",
"Richard",
"Lisa"
};

active<another_worker> other_workers[] = {
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 <ENTER> to exit...");
std::fflush(stdout);
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?

19 Answers

Szabolcs Ferenczi

10/30/2008 9:44:00 PM

0

On Oct 30, 10:39 pm, "Chris M. Thomasson" <n...@spam.invalid> wrote:
> 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(void*);
>
> class thread_base {
>   pthread_t m_tid;
>   friend void* thread_entry(void*);
>   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::~thread_base() {}
>
> void* thread_entry(void* state) {
>   reinterpret_cast<thread_base*>(state)->on_active();
>   return 0;
>
> }
>
> template<typename T>
> struct active : public T {
>   active() : T() {
>     this->active_run();
>   }
>
>   ~active() {
>     this->active_join();
>   }
>
>   template<typename T_p1>
>   active(T_p1 p1) : T(p1) {
>     this->active_run();
>   }
>
>   template<typename 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::string 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)::~my_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<worker> workers[] = {
>       "Chris",
>       "John",
>       "Jane",
>       "Steve",
>       "Richard",
>       "Lisa"
>     };
>
>     active<another_worker> other_workers[] = {
>       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 <ENTER> to exit...");
>   std::fflush(stdout);
>   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.lang.c++/msg/6e915b...

Best Regards,
Szabolcs

Chris M. Thomasson

10/30/2008 9:54:00 PM

0


"Szabolcs Ferenczi" <szabolcs.ferenczi@gmail.com> wrote in message
news:de3350c2-558d-4059-8148-7a1c49f810c4@u29g2000pro.googlegroups.com...
On Oct 30, 10:39 pm, "Chris M. Thomasson" <n...@spam.invalid> wrote:
> > 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.lang.c++/msg/6e915b...

Yeah; I think your right.

Chris M. Thomasson

10/30/2008 10:16:00 PM

0


"Chris M. Thomasson" <no@spam.invalid> wrote in message
news:dIpOk.15$kd5.3@newsfe01.iad...
>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(void*);

class thread_base {
pthread_t m_tid;
friend void* thread_entry(void*);
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::~thread_base() {}

void* thread_entry(void* state) {
reinterpret_cast<thread_base*>(state)->on_active();
return 0;
}


template<typename 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<typename T_p1>
active(T_p1 p1) : T(p1) {
this->active_run();
}

template<typename 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::string 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)::~my_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_base>::guard w12_aw12[] = {
w1, w2, w3,
aw1, aw2, aw3
};

active<worker> workers[] = {
"Jim",
"Dave",
"Regis"
};

active<another_worker> other_workers[] = {
active<another_worker>(999, "Jane"),
active<another_worker>(888, "Ben"),
active<another_worker>(777, "Larry")
};
}

std::puts("\n\n\n__________________\nhit <ENTER> to exit...");
std::fflush(stdout);
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_base>::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.

Adem

10/31/2008 2:40:00 PM

0

"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(void*);
>
> class thread_base {
> pthread_t m_tid;
> friend void* thread_entry(void*);
> 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::~thread_base() {}
>
> void* thread_entry(void* state) {
> reinterpret_cast<thread_base*>(state)->on_active();
> return 0;
> }
>
>
> template<typename 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?

Szabolcs Ferenczi

10/31/2008 6:17:00 PM

0

On Oct 31, 3:40 pm, "Adem" <for-usenet...@alicewho.com> wrote:
> "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(void*);
>
> > class thread_base {
> >   pthread_t m_tid;
> >   friend void* thread_entry(void*);
> >   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::~thread_base() {}
>
> > void* thread_entry(void* state) {
> >   reinterpret_cast<thread_base*>(state)->on_active();
> >   return 0;
> > }
>
> > template<typename 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/wg21/docs/papers/2008...

> 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.lang.c++/browse_frm/thread/f7cae1...

Best Regards,
Szabolcs

Chris M. Thomasson

10/31/2008 6:22:00 PM

0

"Adem" <for-usenet-5c@alicewho.com> wrote in message
news:gef5ep$ihk$1@aioe.org...
> "Chris M. Thomasson" wrote
[...]
>> template<typename 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.lang.c++/browse_frm/thread/f7cae1...

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.

Szabolcs Ferenczi

10/31/2008 7:16:00 PM

0

On Oct 30, 10:39 pm, "Chris M. Thomasson" <n...@spam.invalid> wrote:

> 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_lock<mutex>& lock, Predicate pred);
Effects:
As if:
while (!pred())
wait(lock);
</quote>
http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2008/...
</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<T> b;
public:
BoundedBuffer(const 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<T> b;
public:
BoundedBuffer(const 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

Chris M. Thomasson

10/31/2008 9:02:00 PM

0


"Szabolcs Ferenczi" <szabolcs.ferenczi@gmail.com> wrote in message
news:8390584c-34f0-486d-b19e-4d2bfc40956c@o4g2000pra.googlegroups.com...
On Oct 30, 10:39 pm, "Chris M. Thomasson" <n...@spam.invalid> wrote:

> > 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(void*);

class thread_base {
pthread_t m_tid;
friend void* thread_entry(void*);
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::~thread_base() {}

void* thread_entry(void* state) {
reinterpret_cast<thread_base*>(state)->on_active();
return 0;
}


template<typename 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<typename T_p1>
active(T_p1 p1) : T(p1) {
this->active_run();
}

template<typename 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_init(&m_mutex, NULL);
pthread_cond_init(&m_cond, NULL);
}

~moniter() {
pthread_cond_destroy(&m_cond);
pthread_mutex_destroy(&m_mutex);
}

struct lock_guard {
moniter& m_moniter;

lock_guard(moniter& moniter_) : m_moniter(moniter_) {
m_moniter.lock();
}

~lock_guard() {
m_moniter.unlock();
}
};

void lock() {
pthread_mutex_lock(&m_mutex);
}

void unlock() {
pthread_mutex_unlock(&m_mutex);
}

void wait() {
pthread_cond_wait(&m_cond, &m_mutex);
}

void signal() {
pthread_cond_signal(&m_cond);
}

void broadcast() {
pthread_cond_signal(&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<typename T>
struct bounded_buffer : public moniter {
unsigned const m_max;
std::deque<T> m_buffer;

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

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

T pop() {
T obj;
when (! m_buffer.empty()) {
obj = m_buffer.front();
m_buffer.pop_front();
}
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("produced %u\n", i + 1);
if (! (i % YIELD)) { sched_yield(); }
}
}

public:
producer(bounded_buffer<unsigned>* buffer) : m_buffer(*buffer) {}
};


struct consumer : public thread_base {
bounded_buffer<unsigned>& m_buffer;

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

public:
consumer(bounded_buffer<unsigned>* buffer) : m_buffer(*buffer) {}
};




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

std::puts("\n\n\n__________________\nhit <ENTER> to exit...");
std::fflush(stdout);
std::getchar();
return 0;
}
_______________________________________________________________________







Please take notice of the following class, which compiles fine:


template<typename T>
struct bounded_buffer : public moniter {
unsigned const m_max;
std::deque<T> m_buffer;

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

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

T pop() {
T obj;
when (! m_buffer.empty()) {
obj = m_buffer.front();
m_buffer.pop_front();
}
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.

Chris M. Thomasson

10/31/2008 9:06:00 PM

0

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(void*);

class thread_base {
pthread_t m_tid;
friend void* thread_entry(void*);
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::~thread_base() {}

void* thread_entry(void* state) {
reinterpret_cast<thread_base*>(state)->on_active();
return 0;
}


template<typename 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<typename T_p1>
active(T_p1 p1) : T(p1) {
this->active_run();
}

template<typename 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_init(&m_mutex, NULL);
pthread_cond_init(&m_cond, NULL);
}

~moniter() {
pthread_cond_destroy(&m_cond);
pthread_mutex_destroy(&m_mutex);
}

struct lock_guard {
moniter& m_moniter;

lock_guard(moniter& moniter_) : m_moniter(moniter_) {
m_moniter.lock();
}

~lock_guard() {
m_moniter.unlock();
}
};

void lock() {
pthread_mutex_lock(&m_mutex);
}

void unlock() {
pthread_mutex_unlock(&m_mutex);
}

void wait() {
pthread_cond_wait(&m_cond, &m_mutex);
}

void signal() {
pthread_cond_signal(&m_cond);
}

void broadcast() {
pthread_cond_signal(&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<typename T>
struct bounded_buffer : public moniter {
unsigned const m_max;
std::deque<T> m_buffer;

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

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

T pop() {
T obj;
when (! m_buffer.empty()) {
obj = m_buffer.front();
m_buffer.pop_front();
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("produced %u\n", i + 1);
if (! (i % YIELD)) { sched_yield(); }
}
}

public:
producer(bounded_buffer<unsigned>* buffer) : m_buffer(*buffer) {}
};


struct consumer : public thread_base {
bounded_buffer<unsigned>& m_buffer;

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

public:
consumer(bounded_buffer<unsigned>* buffer) : m_buffer(*buffer) {}
};




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

std::puts("\n\n\n__________________\nhit <ENTER> to exit...");
std::fflush(stdout);
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.

Chris M. Thomasson

10/31/2008 9:15:00 PM

0

What exactly do you have in mind wrt integrating monitor, when keyword and
active object? How far off the corrected version of my example?

http://groups.google.com/group/comp.programming.threads/msg/3e9f79...


BTW, sorry for posting the broken version:

http://groups.google.com/group/comp.programming.threads/msg/e362e9...


I jumped the gun!