上回说到如果有一个请求,分成了很多互不干扰的task,放入了队列里,那么该请求的这些task怎么做同步呢?需要一个同步机制,直接上代码;
class Notification {
public:
Notification() = default;
~Notification() {
}
int32_t init() {
if (init_) return 0;
event_fd_ = eventfd(0,0);
if (event_fd_ < 0) return -1;
epoll_fd = epoll_create(1);
if (epoll_fd < 0) return -2;
struct epoll_event event;
event.data.fd = event_fd_;
event.events = EPOLLIN;
if (epoll_ctl(epoll_fd, EPOLL_CTL_ADD, event_fd_, &event) != 0)
return -3;
init_ = true;
return 0;
}
void set(int32_t num) {
num_ = num;
}
int32_t waitDone() {
while(num_.load(std::memory_order_relaxed) != 0)
wait();
return 0;
}
int32_t Wait() const {
struct epoll_event event;
epoll_wait(epoll_fd_, &event, 1, -1);
uint64_t v;
auto ret = ::read(event_fd_, &v, sizeof(uint64_t));
(void)ret;
return 0;
}
void notify() {
num_.fetch_sub(1, std::memory_order_relaxed);
uint64_t v = 1;
auto ret = ::write(event_fd_, &v, sizeof(uint64_t));
(void)ret;
}
private:
bool init_ {false};
std::atomic<int32_t> num_;
int32_t event_fd_ {-1};
int32_t epoll_fd {-1};
}
使用的时候:
static thread_local Notification* notification = new Notification();
if (notification->init() != 0)
return -1;
notification->set(task_num); // task_num是分成的任务数量
然后在每一个任务里调用
notification->notify();
最后等待所有任务执行完成
notification->wait_done();