Question

I have about 10 objects. Each object is different class. Requests sent to those objects (method calls with returning values) comes from different threads.

I need to synchronise those method calls, that only one must be executed at a time. Some requests have higher priority than the others. It means that if there are more requests waiting to be executed and another one is sent - with higher priority than any other waiting for execution, it shall be executed as next one.

I don't know how to solve this problem in C++. I was thinking about Command pattern but it would require a lot of "manual" coding. I would have to convert each method call into a command object. And the problem is with return value. Does anybody have an idea, what pattern can be used here?

Was it helpful?

Solution

For synchronization, you may use some form of mutual exclusion so that only one thread at a time is manipulating the object.

Dealing with priorities, you will probably want a priority queue with a comparator for determining the criteria for which type of request has greater priority.

Each object would accept a request to do an action and it would have a priority associated with it, and an action (like you suggested with the command pattern). Using a locking mechanism, it would update the priority queue by adding the record, then release it. It must lock the queue because it is accessed via multiple threads. No explicit sorting is necessary -- the queue is always in order of highest priority. Therefore to process a command, simply get the first item in the queue, if one is available, and execute the action.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top