I have two methods (in C#):
List<Pizza> CookPizza(List<Order>);
List<HappyCustomers> DeliverPizza(List<Pizza>);
These operations have no common objects (aside from the pizzas that are passed from one to the other), and are thread-safe. They each take several seconds to execute and they each use different resources (oven vs car). As such, I want to run them at the same time.
How do I organize the threading with these constraints:
I know all of the Orders at the start (say, I have 100,000 of them). An Order can consist of multiple Pizzas and I don't know how many Pizzas are in any Order until after those Pizzas are cooked. (wierd I know). Generally an Order has 1 Pizza, but there can be as many as 10.
The number of active Pizzas should not generally exceed 100. This includes Pizzas freshly cooked and Pizzas being delivered. This is a soft limit, so I can exceed it some (for example, when a big Order was cooked). The hard limit is probably closer to 500.
Both of the operations are more efficient when they are given a lot of work. Generally, CookPizza is most efficient when given at least 20 Orders. Deliver Pizza is most efficient when given at least 50 Pizzas. That is to say, I will see performance degrade if I give fewer items to those methods than those amounts. It's fine to use fewer items if that's all that is left.
The main issue I'm stuggling with is how the methods may need to wait on each other.
I 'd approach this problem using an event-based model to begin with.
Let's say we have a PizzaDispatcher
object which is given the orders. The dispatcher begins calling CookPizza
with a set number of orders from the initial empty state. When pizzas are cooked the CookPizza
function notifies the dispatcher that a pizza has been cooked (perhaps by a callback that you provide as a parameter). When a pizza is delivered the DeliverPizza
function does the same.
The PizzaDispatcher
would now have enough information to decide when and how many pizzas should be turned in for cooking or for delivery based on the number of cooked pizzas and outstanding deliveries.
This can be refactored to using events instead of callbacks etc, but I 'm posting it for the idea, not the specifics of the implementation.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With