Usenet comp.unix.osf.osf1 (1992-2004)
 help / color / mirror / Atom feed
From: David Brownell <brownell@ix.netcom.com>
Subject: Re: Looking for best design for using pthreads in C++ objects
Date: 1996/02/20	[thread overview]
Message-ID: <312A0E5F.7B2C@ix.netcom.com> (raw)
In-Reply-To: 3128ff8b.666031216@news.clark.net

Thom Anderson wrote:

> I have used pthreads from C before but not from C++.  I have a couple of ideas
> in mind but neither is elegant.  Does anyone have any experience with
> C++/Pthreads and no of some good design solutions, tips, or ideas???

One approach that works just fine:  use it from C++ like you use it from C.

If your C++ environment has good pthreads supports, you'll be able to forget
about pushing/popping cleanup handlers since the C++ destructors will do all
of that stuff for you when your thread is canceled.  (Cancel != Kill ...)
You _really_ want that support, else you won't be able to support cancellation
without lots of additional effort.

One of the really nice techniques is to have a "Locker" class to grab mutexes
as needed, and then release it automatically on all exits.  Something like:

	class Locker {
	  public:
				Locker (pthread_mutex_t *lock)
				: mutex (lock) { pthread_mutex_lock (mutex); }
				~Locker () { pthread_mutex_unlock (mutex); }
	  
	    int			wait (pthread_cond_t *cv)
				{ return pthread_cond_wait (cv, mutex); };
	
	  private:
	    pthread_mutex_t	*mutex;
	};

and then use it like

	SomeClass::member_function ( ... arguments ...)
	{
		... do a bunch of work

		Locker (&some_mutex);

		... do more work
		... The mutex is held during this work, and always
		... released on all exits from this function
	}

That kind of class really helps get rid of the bugs you have due
to locks not getting released uniformly on all codepaths.

I've never found a "thread" class to be of any help except as an
excercise to show basic C++ and POSIX.1c skills.  CFRONT used to
have a thread class used for simulations, and there are folk who
evidently like such classes.  Having programmed MT/C++ software
for the past four years or so, I can testify that they're not
necessary.  But of course, your preferred style can differ.

- Dave



  parent reply	other threads:[~1996-02-20  5:00 UTC|newest]

Thread overview: 8+ messages / expand[flat|nested]  mbox.gz  Atom feed  top
1996-02-19  5:00 Looking for best design for using pthreads in C++ objects Thom Anderson
1996-02-20  5:00 ` Nasser Abbasi
1996-02-20  5:00 ` David Brownell [this message]
1996-02-26  5:00   ` Webb Scales
     [not found]     ` <313DEF19.5B69@ix.netcom.com>
     [not found]       ` <313EDB0B.FF6@zko.dec.com>
1996-03-08  5:00         ` David Brownell
1996-02-27  5:00   ` Harald Fuchs
1996-02-28  5:00   ` Webb Scales
1996-03-06  5:00   ` David Brownell
read-only archive

This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox