What sync object should i use?

Juan Manuel Cabo juanmanuel.cabo at gmail.com
Wed May 15 08:35:04 PDT 2013


On Wednesday, 15 May 2013 at 02:25:02 UTC, Heinz wrote:
> ....
> 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;
> ....

It sounds like you need to:
     1) use a Message Queue.
     2) Copy the message while you work on it with the consumer, 
so that you can exit the mutex.

If you don't use a message queue, then the thread that feeds the 
consumer will have to wait on the consumer to finish processing 
the last message, just to post a new message. Thus removing the 
advantage of processing the message in a different thread.

If you use a message queue, make it so that you exit the mutex 
lock while you process the message, and then reaquire the mutex 
to use the message queue. This is so that you can keep adding 
messages to the queue without having to wait until the last 
message is consumed.

There are many ways to implement a queue for thread message 
passing, some are more advanced and require less locking. But you 
can start with a fixed array.

--jm



More information about the Digitalmars-d-learn mailing list