Re: Smart programming languages
From: Bill Godfrey (bill-godfrey_at_sunny-daventry.invalid)
Date: 02/05/05
- Next message: Jim Rogers: "Re: Smart programming languages"
- Previous message: beliavsky_at_aol.com: "Re: Smart programming languages"
- In reply to: Randy Howard: "Re: Smart programming languages"
- Next in thread: Jim Rogers: "Re: Smart programming languages"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
Date: 05 Feb 2005 00:43:43 GMT
Randy Howard <randyhoward@FOOverizonBAR.net> wrote:
> LOCK(some_mutex);
> perf_counter++;
> UNLOCK(some_mutex);
>
> Where LOCK and UNLOCK are macros that call something like
> pthread_mutex_lock and pthread_mutex_unlock() plus all of the error
> handling to go with them and scatter that all over the place.
>
> Instead, it would be guaranteed safe to just type:
>
> perf_counter++;
Slightly beside the point...
C++'s templates could do something similar. Have one template class to hold
the resource in private and have another template class to take the mutex
and have the destructor return the mutex.
Once an instance of the second template class is constructed, it means that
mutex take must have been successful. (Or an exception would have been
thrown.) This class would need a member function to expose a reference to
the original resource help in private by the first template class.
(The second template would need to be a friend of the first.)
For example...
/* Construct our resource. */
ProtectedResource<int> mydata(12);
{
/* Lock it or throw. */
MutexLock<int> mydata_locked(mydata);
/* Use it. */
mydata_locked.getRef() ++;
/* Return lock by mydata_locked falling out of scope. */
}
Or rehaps more succinctly...
ProtectedResource<int> mydata(12);
MutexLock<int>(mydata).getRef() ++;
In this second example, the temporary MutexLock instance will last only as
long as its needed. As a bonus, if any exception occurs whilst the resource
is locked, the destructor will tidy it up for you.
I wrote something similar ages ago for an OS where memory was controlled by
handles which had to be locked. We had a string class which a floating
memory handle and a stringlocker class which would lock the memory in place
and expose a pointer.
Bill, say NO to deferred destructors!
-- http://billpg.me.uk/ usenet(at)billpg(dot)me(dot)uk
- Next message: Jim Rogers: "Re: Smart programming languages"
- Previous message: beliavsky_at_aol.com: "Re: Smart programming languages"
- In reply to: Randy Howard: "Re: Smart programming languages"
- Next in thread: Jim Rogers: "Re: Smart programming languages"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
Relevant Pages
|