From 59ee4ce783e7f896a59a8831fb919ef29e0112aa Mon Sep 17 00:00:00 2001 From: yhy Date: Wed, 25 Dec 2024 19:37:28 +0800 Subject: [PATCH] =?UTF-8?q?iothread=20=E5=88=9D=E6=AD=A5=E5=B0=81=E8=A3=85?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- includes/net/tcp/io_thread.hpp | 21 +++++++++++++++ src/net/tcp/io_thread.cc | 49 ++++++++++++++++++++++++++++++++++ 2 files changed, 70 insertions(+) create mode 100644 includes/net/tcp/io_thread.hpp create mode 100644 src/net/tcp/io_thread.cc diff --git a/includes/net/tcp/io_thread.hpp b/includes/net/tcp/io_thread.hpp new file mode 100644 index 0000000..b1d8d95 --- /dev/null +++ b/includes/net/tcp/io_thread.hpp @@ -0,0 +1,21 @@ +#pragma once +#include "tcp_connection.hpp" +#include +#include + + +namespace tinyrpc { + + class IOThread { + public: + IOThread(); + ~IOThread(); + bool addClient(int fd); + private: + void mainFunc(); + private: + std::unordered_map m_clients; + std::thread m_thread; + }; + +} \ No newline at end of file diff --git a/src/net/tcp/io_thread.cc b/src/net/tcp/io_thread.cc new file mode 100644 index 0000000..6c3813a --- /dev/null +++ b/src/net/tcp/io_thread.cc @@ -0,0 +1,49 @@ +#include "io_thread.hpp" +#include "logger.hpp" +#include "reactor.hpp" +#include "coroutine.hpp" +#include "tcp_connection.hpp" +#include + + +namespace tinyrpc { + static thread_local Reactor* t_reactor = nullptr; + static thread_local IOThread* t_ioThread = nullptr; + IOThread::IOThread() : m_thread(&IOThread::mainFunc, this) { + + } + + IOThread::~IOThread() { + if(m_thread.joinable()) { + m_thread.join(); + } + for(auto& conn : m_clients) { + delete conn.second; + } + m_clients.clear(); + } + + bool IOThread::addClient(int fd) { + if(m_clients.count(fd)) + return false; + m_clients.insert({fd, new TcpConnection(fd)}); + return true; + } + + void IOThread::mainFunc() { + if(t_ioThread) { + logger() << "this thread already built!"; + exit(-1); + } + + if(t_reactor) { + logger() << "this thread:" << std::this_thread::get_id() << " already has reactor!"; + exit(-1); + } + + t_ioThread = this; + t_reactor = new Reactor(Reactor::ReactorType::Sub); + Coroutine::getMainCoroutine(); // 创建协程 + t_reactor->loop(); + } +} \ No newline at end of file