How to use synchronized() {} as the basis for a freely (un)lockable mutex, using stackthreads

Sean Kelly sean at f4.ca
Wed Jan 9 13:06:55 PST 2008


downs wrote:
> Sean Kelly wrote:
>> downs wrote:
>>> Disclaimer: My StackThreads are neither particularly fast (130 cycles
>>> per context switch), nor particularly stable.
>>> This is primarily intended as a Proof of Concept, even though I do use
>>> it in some of my code. :)
>>>
>>> Have you ever wished D had a Mutex class that could be locked or
>>> unlocked at any time?
>> Tango does :-)
>>
> 
> Clarification. D/Phobos.
> 
>>> D's synchronized() {} statement is nice and all, but does have some
>>> weaknesses, primarily that it can only be used to
>>> synchronize some scope - it is not possible to unlock the underlying
>>> mutex in the middle of a block.
>> The Tango mutexes can also be used with the 'synchronized' statement.
>> However, I'm not sure I like the idea of being inside a 'synchronized'
>> block and having the mutex unlocked.  Why not just break the code into
>> two sequential 'synchronized' blocks?
>>
>>
>> Sean
> 
> Because the structure of the code looks like this:
> 
> foo;
> synchronized {
>   bar;
>   whee {
>     lol;
>     *unsynchronized* { lmao; }
>     meep;
>   }
>   baz;
> }
> 
> So, to break it into two synchronized statements, my code would have to look like so ...
> 
> foo;
> synchronized {
>   bar;
>   whee {
>     lol;
> }
>       lmao;
> synchronized {
>     meep;
>   } // closing bracket of whee
>   baz;
> }
> 
> See the problem? :)

I can't say I've ever actually seen the need for such an algorithm in 
practice (outside of condition variables), but in Tango you could do:

synchronized( mutex )
{
    bar;
    whee
    {
       lol;
       {
          mutex.unlock;
          scope(exit) mutex.lock;
          meep;
       }
       baz;
    }
}

Can't say I have a solution for Phobos though.


Sean



More information about the Digitalmars-d mailing list