What sync object should i use?

Heinz thor587 at gmail.com
Tue May 14 19:24:58 PDT 2013


To Steven:

> 1. D mutex locks are re-entrant.  That is, you can do:
>
> synchronized(mutex)
> {
>    synchronized(mutex)
>    {
>       ...
>    }
> }
>
> and all is fine.

Hmmm, i guess this is what the docs meant by "mutexes are 
recursive", i didn't get it at first but now i do.
To test this i wrapped SetLoop() in synchronized(cond.mutex) and 
called it from consumer wich was already all wrapped by the same 
synchronized(cond.mutex), i thought at first it was going to be a 
deadlock but i guess this is what you mean because it works like 
a charm.

Thanks for your code example, i'll update my code with your 
suggestions. But there's one thing i don't understand in your 
example: If the producer is inside a while() generating multiple 
messages once in a while then when the lock is released in the 
consumer, the producer will replace "my_variable" a couple of 
times with the latest message until consumer gets to wait() 
again. That's why i locked the whole consumer, to sync all 
messages. Am i wrong here?

To Sean:

> Let's back up a minute.  Can you be more specific about what 
> you're trying to do?  I think you shouldn't need to use the 
> "loop" var at all, but I'm not entirely sure.  Also, loop and 
> my_variable will be thread-local given how they're declared.

Fair enough, i uploaded a bunch of code hoping that experienced 
programmers like you to understand right away what i'm doing.

I have this "main loop" wich is named here as my consumer 
function. I didn't want this main loop to be cycling all the time 
if there was nothing to do. So i needed an event object 
(condition/mutex) that locked the loop until any of the 2 program 
events (or both) occur:

1) A custom program message was sent by producer to main loop to 
notify for example mouse move, key press, timer tick, etc.
2) The user explicitly want to do something else (execute custom 
code or perform an action not covered by program messages) or did 
something that now needs to be processed inside the main loop. In 
this case the user calls SetLoop(true) to notify the main loop 
and then do what the user want.

That's why i have and need both types of messages: bool loop; and 
Object my_variable;

My code seems to work fine but i did not know if it was the best 
approach. Now i know after your help that i can and must protect 
both messages with the condition's mutex and have all in sync. 
Also i learned that wait() and notify() must be inside a lock.

To ALL:

Sorry for my incompetence. I'm not new to D but i am to D2 and 
multithreading. I got stuck in D1, specially in the DMD1.030 era 
(those were the most stable and beautiful times) but now i 
decided it was time to evolve. So far, learning D2 and 
multithreading hasn't been easy, but with your help guys i've 
accomplished many things.

Thank you again for your support.


More information about the Digitalmars-d-learn mailing list