载入中...
搜索中...
未找到
NetWorker.cpp
浏览该文件的文档.
1#include "network/NetWorker.h"
2#include "network/Network.h"
3
4#include <chrono>
5
6namespace eve::network {
7
8NetWorker::NetWorker(Network* owner) : owner_(owner) {}
9
13
15 if (running_) return;
16 running_ = true;
17 thread_ = std::thread([this] { threadMain(); });
18}
19
21 running_ = false;
22 cv_.notify_all();
23 // A job may request shutdown from the worker itself. Joining the current
24 // thread would deadlock; leave it joinable for the owner/destructor.
25 if (thread_.joinable() && thread_.get_id() != std::this_thread::get_id()) thread_.join();
26}
27
29 std::lock_guard<std::mutex> lock(mu_);
30 completions_.push_back(std::move(c));
31}
32
33void NetWorker::drain(std::vector<NetCompletion>& out) {
34 std::lock_guard<std::mutex> lock(mu_);
35 out.swap(completions_);
36}
37
38void NetWorker::submit(std::function<void()> job) {
39 {
40 std::lock_guard<std::mutex> lock(mu_);
41 jobs_.push_back(std::move(job));
42 }
43 cv_.notify_one();
44}
45
46void NetWorker::threadMain() {
47 while (true) {
48 std::vector<std::function<void()>> batch;
49 {
50 std::unique_lock<std::mutex> lock(mu_);
51 cv_.wait_for(lock, std::chrono::milliseconds(5), [this] {
52 return !running_ || !jobs_.empty();
53 });
54 if (!running_ && jobs_.empty()) break;
55 batch.swap(jobs_);
56 }
57 for (auto& job : batch) {
58 if (job) job();
59 }
60 if (owner_) owner_->pollSockets();
61 }
62}
63
64} // namespace eve::network
std::int32_t c
void drain(std::vector< NetCompletion > &out)
Test helper: moves all pending completions into out.
Definition NetWorker.cpp:33
void post(NetCompletion c)
Queues a completion for the main thread (thread-safe).
Definition NetWorker.cpp:28
void stop()
Stops the worker thread and joins it.
Definition NetWorker.cpp:20
NetWorker(Network *owner)
Creates a worker owned by owner (not started yet).
Definition NetWorker.cpp:8
void start()
Starts the worker thread.
Definition NetWorker.cpp:14
~NetWorker()
Net worker.
Definition NetWorker.cpp:10
void submit(std::function< void()> job)
Queues an arbitrary blocking job to run on the worker thread.
Definition NetWorker.cpp:38
Network module: TCP/UDP/HTTP factories, background worker, and completion event plumbing....
Definition Network.h:35
One asynchronous network result/event. handle points at the originating TcpSocket/UdpSocket/HttpReque...
Definition NetTypes.h:33