载入中...
搜索中...
未找到
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 if (!running_) return;
22 {
23 std::lock_guard<std::mutex> lock(mu_);
24 running_ = false;
25 }
26 cv_.notify_all();
27 if (thread_.joinable()) thread_.join();
28}
29
31 std::lock_guard<std::mutex> lock(mu_);
32 completions_.push_back(std::move(c));
33}
34
35void NetWorker::drain(std::vector<NetCompletion>& out) {
36 std::lock_guard<std::mutex> lock(mu_);
37 out.swap(completions_);
38}
39
40void NetWorker::submit(std::function<void()> job) {
41 {
42 std::lock_guard<std::mutex> lock(mu_);
43 jobs_.push_back(std::move(job));
44 }
45 cv_.notify_one();
46}
47
48void NetWorker::threadMain() {
49 while (true) {
50 std::vector<std::function<void()>> batch;
51 {
52 std::unique_lock<std::mutex> lock(mu_);
53 cv_.wait_for(lock, std::chrono::milliseconds(5), [this] {
54 return !running_ || !jobs_.empty();
55 });
56 if (!running_ && jobs_.empty()) break;
57 batch.swap(jobs_);
58 }
59 for (auto& job : batch) {
60 if (job) job();
61 }
62 if (owner_) owner_->pollSockets();
63 }
64}
65
66} // namespace eve::network
uint32_t c
void drain(std::vector< NetCompletion > &out)
Test helper: moves all pending completions into out.
Definition NetWorker.cpp:35
void post(NetCompletion c)
Queues a completion for the main thread (thread-safe).
Definition NetWorker.cpp:30
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
void submit(std::function< void()> job)
Queues an arbitrary blocking job to run on the worker thread.
Definition NetWorker.cpp:40
Network module: TCP/UDP/HTTP factories, background worker, and completion event plumbing....
Definition Network.h:30
void pollSockets()
Internal: polls watched sockets; called from the NetWorker thread.
Definition Network.cpp:213
One asynchronous network result/event. handle points at the originating TcpSocket/UdpSocket/HttpReque...
Definition NetTypes.h:33