Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pizza, Threading, Waiting, Notifying. What does it mean?

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.

  • DeliverPizza might need to wait around for CookPizza to complete 50.
  • CookPizza might need to wait around for DeliverPizza to reduce the number of active Pizzas to 100.
like image 572
Amy B Avatar asked Apr 11 '11 12:04

Amy B


1 Answers

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.

like image 96
Jon Avatar answered Nov 06 '22 17:11

Jon