I am trying to implement a stock exchange using Hoare's monitors.
It has two functions buy() and sell() as follow:
buy(procid, ticker, nshares, limit)
sell(procid, ticker, nshares, limit)
And should print information on buyer id, seller id, ticker, number of shares, and price. And fairness is always satisfied.
The pseudo-code of my solution is as follows, but it's not complete. It basically uses a condition variable queue for each ticker. A seller process is put to sleep on this queue when it sends a sell order to the stock exchange, and a buyer process signals this seller process that it wants to buy if the conditions (matching price limit and number of shares) are satisfied.
monitor SE {
int available_shares;
int price;
sell(procid, ticker, nshares, limit) {
wait(ticker); // put sell order in ticker queue
available_shares += nshares;
price = limit;
printf("Starting transaction with seller %i", procid);
}
buy(procid, ticker, nshares, limit) {
if (limit <= price && nshares <= available_shares) {
signal(ticker);
available_share -= nshares;
printf("Completing transaction with buyer %i", procid);
printf("Transacting %i %s shares at %i", nshares, ticker, limit);
} else {
wait(ticker); // put buy order in ticker queue
}
}
}
Would such an approach be able to handle multiple buy and sell orders for multiple tickers? Or does it lead to a dead-end?