Simple lock
Alf P. Steinbach
alfps at start.no
Sat Mar 20 00:15:08 EDT 2010
* MRAB:
> Gabriel Genellina wrote:
>> En Fri, 19 Mar 2010 23:31:23 -0300, MRAB <python at mrabarnett.plus.com>
>> escribió:
>>> moerchendiser2k3 wrote:
>>
>>>> class SetPointer
>>>> {
>>>> private:
>>>> void *ptr;
>>>> MY_LOCK lock;
>>>> public:
>>>> void SetPointer(void *p)
>>>> {
>>>> Lock(this->lock);
>>>> this->ptr = p;
>>>> }
>>
>>> 3. You're locking, but never unlocking. The sequence should be: lock, do
>>> stuff, unlock.
>>
>> Just FYI: C++ doesn't have try/finally, and such behavior is usually
>> emulated using a local object. When it goes out of scope, it is
>> automatically destroyed, meaning that the object destructor is called.
>> Whatever you would write in a "finally" clause, in C++ goes into a
>> destructor.
>>
>> Of course C++ guys would never say they're "emulating" try/finally,
>> instead they declare RAII as *the* Only and Right Way :)
>>
> Lock() doesn't look like a declaration, but a function call (although
> it's been a while since I last did C++!).
Right. But the OP is clearly a beginner who has yet to learn conventions (like
all uppercase reserved for macros) and good versus bad programming constructs
(like using void*), and who is even confusing C++ with Python. So it might just
be that 'Lock' is a macro, and then it can expand to anything.
> In the past I've written some C++ code where try..finally... would've
> been useful... *sigh*
Check out Marginean and Alexandrescu's ScopeGuard. Old DDJ-article. For MSVC you
may want to change use of __LINE__ in that code, to MS-specific __COUNTER__.
Fwiw. I can't remember ever needing 'finally' in C++ code.
It indicates a lack of encapsulation of entitites that should clean up
themselves. Simple smart pointers etc. can help. E.g., check out Boost library.
Cheers & hth., even if a little off-topic,
- Alf
More information about the Python-list
mailing list