forked from dmlc/ps-lite
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcustomer.cc
66 lines (57 loc) · 1.77 KB
/
customer.cc
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
/**
* Copyright (c) 2015 by Contributors
*/
#include "ps/internal/customer.h"
#include "ps/internal/postoffice.h"
namespace ps {
const int Node::kEmpty = std::numeric_limits<int>::max();
const int Meta::kEmpty = std::numeric_limits<int>::max();
Customer::Customer(int id, const Customer::RecvHandle& recv_handle)
: id_(id), recv_handle_(recv_handle) {
Postoffice::Get()->AddCustomer(this);
recv_thread_ = std::unique_ptr<std::thread>(new std::thread(&Customer::Receiving, this));
}
Customer::~Customer() {
Postoffice::Get()->RemoveCustomer(this);
Message msg;
msg.meta.control.cmd = Control::TERMINATE;
recv_queue_.Push(msg);
recv_thread_->join();
}
int Customer::NewRequest(int recver) {
std::lock_guard<std::mutex> lk(tracker_mu_);
int num = Postoffice::Get()->GetNodeIDs(recver).size();
tracker_.push_back(std::make_pair(num, 0));
return tracker_.size() - 1;
}
void Customer::WaitRequest(int timestamp) {
std::unique_lock<std::mutex> lk(tracker_mu_);
tracker_cond_.wait(lk, [this, timestamp]{
return tracker_[timestamp].first == tracker_[timestamp].second;
});
}
int Customer::NumResponse(int timestamp) {
std::lock_guard<std::mutex> lk(tracker_mu_);
return tracker_[timestamp].second;
}
void Customer::AddResponse(int timestamp, int num) {
std::lock_guard<std::mutex> lk(tracker_mu_);
tracker_[timestamp].second += num;
}
void Customer::Receiving() {
while (true) {
Message recv;
recv_queue_.WaitAndPop(&recv);
if (!recv.meta.control.empty() &&
recv.meta.control.cmd == Control::TERMINATE) {
break;
}
recv_handle_(recv);
if (!recv.meta.request) {
std::lock_guard<std::mutex> lk(tracker_mu_);
tracker_[recv.meta.timestamp].second++;
tracker_cond_.notify_all();
}
}
}
} // namespace ps