🚀 go-pugleaf

RetroBBS NetNews Server

Inspired by RockSolid Light RIP Retro Guy

Article View: comp.programming.threads
Article #4

Re: Looking for best design for using pthreads in C++ objects

#4
From: David Brownell
Date: Tue, 20 Feb 1996 18:09
54 lines
2569 bytes
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
Technical Details
Message-ID: <312A0E5F.7B2C@ix.netcom.com>
Path: arc1-ca.pugleaf.net!ix.netcom.com!netnews
References: <3128ff8b.666031216@news.clark.net>

Show Full Headers
Complete Article Headers
Path: arc1-ca.pugleaf.net!ix.netcom.com!netnews
From: David Brownell <brownell@ix.netcom.com>
Newsgroups: comp.programming.threads,comp.lang.c++,comp.unix.osf.osf1,comp.unix.programmer,comp.object
Subject: Re: Looking for best design for using pthreads in C++ objects
Date: Tue, 20 Feb 1996 10:09:35 -0800
Organization: Dave's VAX
Message-ID: <312A0E5F.7B2C@ix.netcom.com>
References: <3128ff8b.666031216@news.clark.net>
NNTP-Posting-Host: pax-ca8-25.ix.netcom.com
Mime-Version: 1.0
Content-Type: text/plain; charset=us-ascii
Content-Transfer-Encoding: 7bit
X-NETCOM-Date: Tue Feb 20 10:13:30 AM PST 1996
X-Mailer: Mozilla 2.0 (Win95; I)