2024-12-25 19:37:28 +08:00
|
|
|
#include "io_thread.hpp"
|
|
|
|
#include "logger.hpp"
|
|
|
|
#include "reactor.hpp"
|
|
|
|
#include "coroutine.hpp"
|
|
|
|
#include "tcp_connection.hpp"
|
|
|
|
#include <thread>
|
|
|
|
|
|
|
|
|
|
|
|
namespace tinyrpc {
|
|
|
|
static thread_local Reactor* t_reactor = nullptr;
|
|
|
|
static thread_local IOThread* t_ioThread = nullptr;
|
|
|
|
|
2025-01-10 15:00:50 +08:00
|
|
|
|
|
|
|
// static IOThread* getThisIoThread() {
|
|
|
|
// return t_ioThread;
|
|
|
|
// }
|
|
|
|
|
|
|
|
IOThread::IOThread() : m_thread(&IOThread::mainFunc, this) {
|
|
|
|
logger() << "IO Thread is built";
|
2024-12-25 19:37:28 +08:00
|
|
|
}
|
|
|
|
|
2025-01-10 15:00:50 +08:00
|
|
|
// void IOThread::removeFd(int fd) { // TODO 加锁 ?
|
|
|
|
// auto it = m_clients.find(fd);
|
|
|
|
// if(it == m_clients.end()) return;
|
|
|
|
// delete it->second;
|
|
|
|
// m_clients.erase(it);
|
|
|
|
// }
|
|
|
|
|
|
|
|
void IOThread::addClient(int fd) {
|
|
|
|
if(m_clients.count(fd)) {
|
|
|
|
delete m_clients[fd];
|
|
|
|
}
|
|
|
|
m_clients.insert({fd, new TcpConnection(fd, m_reactor)});
|
2024-12-25 19:37:28 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
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;
|
2025-01-10 15:00:50 +08:00
|
|
|
m_reactor = t_reactor = new Reactor(Reactor::ReactorType::Sub);
|
2024-12-25 19:37:28 +08:00
|
|
|
Coroutine::getMainCoroutine(); // 创建协程
|
2025-01-10 15:00:50 +08:00
|
|
|
m_reactor->loop();
|
|
|
|
}
|
|
|
|
|
|
|
|
IOThread::~IOThread() {
|
|
|
|
m_reactor->stop();
|
|
|
|
if(m_thread.joinable()) {
|
|
|
|
m_thread.join();
|
|
|
|
}
|
|
|
|
delete m_reactor;
|
|
|
|
for(auto& conn : m_clients) {
|
|
|
|
delete conn.second;
|
|
|
|
}
|
|
|
|
m_clients.clear();
|
2024-12-25 19:37:28 +08:00
|
|
|
}
|
|
|
|
}
|