include <iostream>
include <string>
include <queue>
include <thread>
include <chrono>
include <limits.h>
include <condition_variable>
include <fstream>
include <unordered_map>
include "json/json.h"
using namespace std;
using namespace chrono;
define DEFAULT_MAX_QUEUE_SIZE 1000
// couries information
struct Courier {
string id;
string courierId;//
string foodid;
int64_t arriveTime; // courier arrived
bool operator < (const Courier &co) const {
return arriveTime < co.arriveTime;
}
bool operator > (const Courier &co) const {
return arriveTime > co.arriveTime;
}
};
struct Food {
string name;
int prepareTime; // s
};
// order information
struct Order{
string id;
Food food;
int state;
int64_t dispatchTime; // order received, courier dispatched
int64_t finishTime; // order prepared
bool operator < (const Order &od) const
{
return finishTime < od.finishTime;
}
bool operator > (const Order &od) const
{
return finishTime > od.finishTime;
}
};
// order received, order prepared, courier
// dispatched, courier arrived, order picked up
typedef int (RANDRANGE)(int min, int max);
typedef int (Check)(void *data, int64_t tms);
void EventLog(string str)
{
cout<<"event: "<<str<<endl;
}
void DebugLog(string str)
{
cout<<"debug: "<<str<<endl;
}
void ErrorLog(string str)
{
cout<<"error: "<<str<<endl;
}
class Notify {
public:
virtual int NotifyEvent(int event, void *data) = 0;
};
struct Node {
void *data; // hashmap, order or couries
void *param; // user param
int64_t tms; // event time
int event; // events
Notify *notify;
uint64_t id;
bool operator < (const Node &node) const {
return tms < node.tms;
}
bool operator > (const Node &node) const {
return tms > node.tms;
}
};
define INTERVAL 500
class Timer {
private:
std::mutex mtx;
priority_queue<Node, vector<Node>, greater<Node>> que;
bool running;
int interval; // ms
public:
Timer() {
interval = INTERVAL;
running = true;
}
int32_t SetInterval(int interval); // ms
int32_t InsertNode(Node node) {
std::lock_guard<std::mutex> guard(mtx);
//cout<<"insert node "<<node.tms<<endl;
cout<<"insert node"<<node.id<<" event "<<node.event<< " "<<node.tms<<endl;
que.push(node);
}
void TimerRun() {
// cout<<"Time Run\n";
while (running) {
std::this_thread::sleep_for(std::chrono::milliseconds(interval));
std::lock_guard<std::mutex> guard(mtx);
auto now = duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
//cout<<"timer cmp: "<<que.top().tms <<" "<<now<<endl;
while (!que.empty() && que.top().tms < now) {
Node t = que.top();
cout<<"touch "<<t.id<<" event "<<t.event<<" "<<t.tms<<endl;
t.notify->NotifyEvent(t.event, &t);
// cout<<t.tms<<" remove\n";
que.pop();
// cout<<"que size: "<<que.size()<<endl;
}
}
}
};
template<typename NODE>
class MyQueue {
public:
virtual int Init(int cap) = 0;
virtual void Deinit() = 0;
virtual bool IsFull(void) = 0;
virtual bool IsEmpty(void) = 0;
virtual int Size(void) = 0;
virtual int Insert(string id, NODE data) = 0;
};
template<typename NODE>
class HashQueue : public MyQueue<NODE> {
public:
HashQueue() {
this->capicity = DEFAULT_MAX_QUEUE_SIZE;
}
int Init(int cap)
{
this->capicity = cap;
}
void Deinit()
{
// auto it = que.begin();
// while (it != que.end()) {
que.clear();
//}
return;
}
int Insert(string id, NODE order)
{
//cout<<"input order id: "<<order.id<<endl;
if (this->que.size() >= this->capicity) {
return -1;
}
if (que.count(id)) {
// cout error
}
que[id] = order;
return 0;
}
bool IsFull() {
return this->que.size() == this->capicity;
}
bool IsEmpty() {
return this->que.empty();
}
bool FindValById(string id) {
return que.count(id) > 0;
}
NODE GetValbyId(string id) {
return que[id];
}
int Size() {
return que.size();
}
private:
int capicity;
unordered_map<string, NODE> que;
};
template<typename NODE>
class ProQueue : public MyQueue<NODE> {
public:
ProQueue() {
this->capicity = DEFAULT_MAX_QUEUE_SIZE;
}
int Init(int cap)
{
this->capicity = cap;
}
void Deinit()
{
while (!this->que.empty()) {
this->que.pop();
}
return;
}
int Insert(string id, NODE order)
{
(void)id;
if (this->que.size() >= this->capicity) {
return -1;
}
this->que.push(order);
return 0;
}
bool IsFull() {
return this->que.size() == this->capicity;
}
bool IsEmpty() {
return this->que.empty();
}
NODE GetFrontAndPop() {
NODE order = this->que.top();
this->que.pop();
return order;
}
int Size() {
return this->que.size();
}
private:
int capicity;
priority_queue<NODE, vector<NODE>, greater<NODE>> que;
};
static int Randrange(int min, int max)
{
if (max <= min) {
return -1;
}
return min + rand() % (max - min);
}
define PREPARED 1
define ARRIED 2
struct Param{
MyQueue<Order*> orders;
MyQueue<Courier> *couriers;
};
class Dispatch : public Notify {
public:
Dispatch() {
range = nullptr;
srand((unsigned)time(NULL));
}
virtual int DispatchOrder(Order* order, MyQueue<Courier> couriers, MyQueue<Order> orders) = 0;
virtual int DispatchCouries(Courier courier, MyQueue<Order> orders, MyQueue<Courier> couriers) = 0;
int NotifyEvent(int event, void data)
{
Node node = (Node)data;
// cout<<"notify event: "<<event<<endl;
if (event == PREPARED) {
NotifyOrderPrepared((Order)node->data);
DispatchOrder((Order)node->data, ((Param *)node->param)->couriers, ((Param *)node->param)->orders);
}
if (event == ARRIED) {
NotifyCourierArrived((Courier*)node->data);
DispatchCouries((Courier*)node->data, ((Param *)node->param)->orders, ((Param *)node->param)->couriers);
}
}
int NotifyOrderPrepared(void *data)
{
Order* order = (Order*)data;
cout<<"order id: "<<order->id<<" prepared addr: "<<order<<endl;
}
int NotifyCourierArrived(void *data)
{
Courier* cou = (Courier*)data;
cout<<"courier id: "<<cou->courierId<<" arrived addr: "<<cou<<endl;
}
void SetSize(int size) {
this->size = size;
}
bool IsStaties()
{
if (size <= orders) {
return true;
}
return false;
}
int RegistRand(RANDRANGE rg) {
range = rg;
}
int CariesArrivedTime(int min, int max)
{
if (range != nullptr) {
return range(min, max);
}
return Randrange(min, max);
}
void AddFoodWait(int prepareTime)
{
this->foodwait += prepareTime;
}
int64_t GetFoodWait()
{
return foodwait;
}
void AddCariesWait(int wait)
{
this->carieswait += wait;
}
int64_t GetCariesWait()
{
return carieswait;
}
void AddOrders() {
orders++;
}
int64_t GetOrders() {
return orders;
}
int64_t GetAvgFoodWaitTime() {
if (orders == 0) {
return 0;
}
return foodwait / orders;
}
int64_t GetAvgCouriersWaitTime() {
if (orders == 0) {
return 0;
}
return carieswait / orders;
}
private:
RANDRANGE range;
int64_t foodwait;
int64_t carieswait;
int64_t orders;
int size;
};
class Matched : public Dispatch
{
public:
int DispatchOrder(Order* order, MyQueue<Courier> couriers, MyQueue<Order> orders) {
HashQueue<Courier> hs = (HashQueue<Courier>)couriers;
if (hs->FindValById(order->id)) {
Courier *courier = hs->GetValbyId(order->id);
// get val
AddCariesWait(order->finishTime - courier->arriveTime );
AddOrders();
cout<<"dispatched order "<<order->id << " to courier "<<courier->courierId<<" orders: "<<GetOrders()<<endl;
if (IsStaties()) {
cout<<"avg food wait time: "<<GetAvgFoodWaitTime()<<" ms\n";
cout<<"avg couries wait time: "<<GetAvgCouriersWaitTime()<<" ms\n";
}
// deispatch
// change state
} else {
orders->Insert(order->id, order);
}
// not find courier
return -1;
}
int DispatchCouries(Courier* courier, MyQueue<Order*> *orders, MyQueue<Courier*> *couriers)
{
HashQueue<Order*> *od = (HashQueue<Order*>*)orders;
if (od->FindValById(courier->id)) {
Order *order = od->GetValbyId(courier->id);
AddFoodWait(courier->arriveTime - order->finishTime);
AddOrders();
cout<<"dispatched order "<<order->id << " to courier "<<courier->courierId<<" orders: "<<GetOrders()<<endl;
if (IsStaties()) {
cout<<"avg food wait time: "<<GetAvgFoodWaitTime()<<" ms\n";
cout<<"avg couries wait time: "<<GetAvgCouriersWaitTime()<<" ms\n";
}
} else {
couriers->Insert(courier->foodid, courier);
}
// not find order
return -1;
}
};
class FIFO : public Dispatch
{
public:
int DispatchOrder(Order* order, MyQueue<Courier> couriers, MyQueue<Order> orders) {
ProQueue<Courier> hs = (ProQueue<Courier>)couriers;
if (!hs->IsEmpty()) {
Courier *courier = hs->GetFrontAndPop();
AddCariesWait(order->finishTime - courier->arriveTime );
AddOrders();
cout<<"FIFO dispatched order "<<order->id << " to courier "<<courier->courierId<<" orders: "<<GetOrders()<<endl;
if (IsStaties()) {
cout<<"avg food wait time: "<<GetAvgFoodWaitTime()<<" ms\n";
cout<<"avg couries wait time: "<<GetAvgCouriersWaitTime()<<" ms\n";
}
// remove
// delete courier;
// delete order;
// // get val
// deispatch
// change state
// free pointer
} else {
orders->Insert(order->id, order);
}
// not find courier
return -1;
}
int DispatchCouries(Courier* courier, MyQueue<Order*> *orders, MyQueue<Courier*> *couriers)
{
ProQueue<Order*> *hs = (ProQueue<Order*>*)orders;
if (!hs->IsEmpty()) {
Order *order = hs->GetFrontAndPop();
AddFoodWait(courier->arriveTime - order->finishTime);
AddOrders();
cout<<"FIFO dispatched order "<<order->id << " to courier "<<courier->courierId<<" orders: "<<GetOrders()<<endl;
if (IsStaties()) {
cout<<"avg food wait time: "<<GetAvgFoodWaitTime()<<" ms\n";
cout<<"avg couries wait time: "<<GetAvgCouriersWaitTime()<<" ms\n";
}
// delete courier;
// delete order;
// get val
// deispatch
// change state
} else {
couriers->Insert(courier->id, courier);
}
// not find order
return -1;
}
};
enum STRATEGIE {
STRATEGIE_MATCH = 0x01, // match strategie
STRATEGIE_FIFO // fifo strategie
};
struct Config {
STRATEGIE st;
int32_t cap;
};
class Server{
private:
std::condition_variable vals;
std::mutex mtx; // 保护
int64_t capicity;
int stragegie; // 策略
Dispatch dispatch;
MyQueue<Order> orders; //
MyQueue<Courier> *couriers; //
Timer timer;
bool dispatching;
public:
int InitServer(Config *conf);
void DeInitServer();
int ReadData(const char* file);
int DispatchOrder();
int Statistics();
};
int Server::Statistics()
{
int64_t fw = dispatch->GetAvgFoodWaitTime();
int64_t cw = dispatch->GetAvgCouriersWaitTime();
cout.flush();
cout<<("food wait time: " + to_string(fw) + "ms couries wait time: " + to_string(cw));
return 0;
}
int Server::DispatchOrder()
{
timer.TimerRun();
}
int Server::InitServer(Config *conf)
{
// default conf
if (conf == NULL) {
stragegie = STRATEGIE_MATCH;
capicity = 10;
} else {
stragegie = conf->st;
capicity = conf->cap;
}
if (stragegie == STRATEGIE_MATCH) {
Matched *match = new Matched();
dispatch = (Dispatch*)match;
this->orders = new HashQueue<Order*>();
this->couriers = new HashQueue<Courier*>();
} else if (stragegie == STRATEGIE_FIFO) {
FIFO *fifo = new FIFO();
dispatch = (Dispatch*)fifo;
this->orders = new ProQueue<Order*>();
this->couriers = new ProQueue<Courier*>();
}
dispatching = true;
return 0;
}
// order received, order prepared, courier dispatched, courier arrived, order picked up)
int Server::ReadData(const char* filename)
{
Json::Reader reader;
Json::Value root;
std::ifstream is;
static int64_t cid = 0;
static int64_t eventid = 0;
static Param param = {
this->orders,
this->couriers
};
is.open(filename, std::ios::binary);
if (reader.parse(is, root, false)) {
int size = root.size();
cout<<"size "<<size<<endl;
dispatch->SetSize(size);
for (int i = 0; i < size;) {
int j = 0;
for (; j < 2 && i + j < size;) {
Order *order = new Order();
Courier *courier = new Courier();
Json::Value tmp = root[i + j];
//order->id = tmp["id"].asString();
order->id = to_string(cid);
order->food.name = tmp["name"].asString();
order->food.prepareTime = tmp["prepTime"].asInt() * 1000;
order->dispatchTime = duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
order->finishTime = order->dispatchTime + order->food.prepareTime;
int rnd = dispatch->CariesArrivedTime(3, 15);
courier->arriveTime = order->dispatchTime + rnd * 1000;
courier->courierId = to_string(cid);
courier->foodid = order->id;
//cout<<" dispatched order: "<<order->id <<" to courier: "<<courier->courierId<<endl;
cid++;
Node orderEvent;
orderEvent.tms = order->finishTime;
orderEvent.data = order;
orderEvent.notify = dispatch;
orderEvent.event = 1;
orderEvent.id = eventid++;
orderEvent.param = ¶m;
Node courierEvent;
courierEvent.tms = courier->arriveTime;
courierEvent.data = courier;
courierEvent.notify = dispatch;
courierEvent.event = 2;
courierEvent.param = ¶m;
courierEvent.id = eventid++;
cout<<"insert order "<<order->id<<"dis time "<<order->dispatchTime<<" finish time "<<order->finishTime<<endl;
//orders->Insert(order->id, order);
cout<<"insert courier "<<courier->id<<"rnd "<<rnd<<" arrive time "<<courier->arriveTime<<endl;
// couriers->Insert(courier->id, courier);
timer.InsertNode(orderEvent);
timer.InsertNode(courierEvent);
// add to timer
j++;
}
i += j;
std::this_thread::sleep_for(2000ms);
}
} else {
cout<<"open file "<<filename<<" failed\n";
}
cout<<"close file \n";
is.close();
return 0;
}
int ProductOrder(Server* server, const char* file)
{
pthread_setname_np(pthread_self(), "product");
return server->ReadData(file);
}
int DispatchOrder(Server* server)
{
pthread_setname_np(pthread_self(), "dispatch");
return server->DispatchOrder();
}
int main(int argc, const char* argv[])
{
Config conf;
conf.st = STRATEGIE_FIFO; // STRATEGIE_FIFO
string file = "data.json";
if (argc == 3) {
conf.st = (STRATEGIE)atoi(argv[1]);
file = argv[2];
}
if (conf.st != STRATEGIE_MATCH && conf.st != STRATEGIE_FIFO) {
cout<<"error stragegie : "<<conf.st<<endl;
}
conf.cap = 10000;
Server server;
server.InitServer(NULL);
thread read(ProductOrder, &server, file.c_str());
thread disp(DispatchOrder, &server);
read.join();
disp.join();
}