From mboxrd@z Thu Jan 1 00:00:00 1970 X-Google-Language: ENGLISH,ASCII-7-bit X-Google-Thread: fc89c,870f39ca0a91dafa X-Google-Attributes: gidfc89c,public X-Google-Thread: 109fba,870f39ca0a91dafa X-Google-Attributes: gid109fba,public X-Google-Thread: 1108a1,870f39ca0a91dafa X-Google-Attributes: gid1108a1,public X-Google-Thread: ffc1e,870f39ca0a91dafa X-Google-Attributes: gidffc1e,public X-Google-Thread: fee84,870f39ca0a91dafa X-Google-Attributes: gidfee84,public From: David Brownell Subject: Re: Looking for best design for using pthreads in C++ objects Date: 1996/02/20 Message-ID: <312A0E5F.7B2C@ix.netcom.com>#1/1 X-Deja-AN: 140311568 references: <3128ff8b.666031216@news.clark.net> content-type: text/plain; charset=us-ascii organization: Dave's VAX x-netcom-date: Tue Feb 20 10:13:30 AM PST 1996 mime-version: 1.0 newsgroups: comp.programming.threads,comp.lang.c++,comp.unix.osf.osf1,comp.unix.programmer,comp.object x-mailer: Mozilla 2.0 (Win95; I) 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