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: ffc1e,870f39ca0a91dafa X-Google-Attributes: gidffc1e,public X-Google-Thread: 109fba,870f39ca0a91dafa X-Google-Attributes: gid109fba,public X-Google-Thread: 1108a1,870f39ca0a91dafa X-Google-Attributes: gid1108a1,public X-Google-Thread: fee84,870f39ca0a91dafa X-Google-Attributes: gidfee84,public From: Webb Scales Subject: Re: Looking for best design for using pthreads in C++ objects Date: 1996/02/26 Message-ID: <31320705.41C6@zko.dec.com>#1/1 X-Deja-AN: 141409055 references: <3128ff8b.666031216@news.clark.net> <312A0E5F.7B2C@ix.netcom.com> content-type: text/plain; charset=us-ascii organization: Digital Equipment Corporation, DECthreads 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 (X11; I; OSF1 V3.2 alpha) David Brownell wrote: > 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. [...] > That kind of class really helps get rid of the bugs you have due > to locks not getting released uniformly on all codepaths. Hmmm...this approach makes me nervous. I assert that it's better to neglect to unlock a mutex than to unlock it when you shouldn't have. For instance, if a thread holding a mutex via the "Locker" class terminates prematurely (due to an exception or cancellation), then the mutex will be unlocked automagically, despite the fact that whatever it was supposed to protect is now likely to be in an inconsistent state. If the process manages to survive losing this thread, then any subsequent accesses to the shared data could easily be disastrous in subtle ways. It would have been much better to have just left the mutex locked! (That is, a deadlock would be much easier to debug than a memory corruptor.) The missing piece is that the destructor for Locker, prior to releasing the mutex, must restore the shared data that the mutex protects to a consistent state. In order to do this, the destructor requires intimate knowledge of what the lock is protecting -- this invalidates the "generic" approach. It would be much better to encapsulate the mutex together with the shared data as some sort of compound object. Then it would be feasible to have the proper clean-up built in. And then it would be OK to be unlocking the mutex automagically. :-) -- ------------------------------------------------------------------------ Webb Scales Digital Equipment Corporation scales@wtfn.enet.dec.com 110 Spit Brook Rd, ZKO2-3/Q18 Voice: 603.881.2196, FAX: 603.881.0120 Nashua, NH 03062-2711 Rule #12: Be joyful -- seek the joy of being alive. ------------------------------------------------------------------------