#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(); } }