iothread 初步封装
This commit is contained in:
parent
1454bfe044
commit
59ee4ce783
21
includes/net/tcp/io_thread.hpp
Normal file
21
includes/net/tcp/io_thread.hpp
Normal file
@ -0,0 +1,21 @@
|
|||||||
|
#pragma once
|
||||||
|
#include "tcp_connection.hpp"
|
||||||
|
#include <thread>
|
||||||
|
#include <unordered_map>
|
||||||
|
|
||||||
|
|
||||||
|
namespace tinyrpc {
|
||||||
|
|
||||||
|
class IOThread {
|
||||||
|
public:
|
||||||
|
IOThread();
|
||||||
|
~IOThread();
|
||||||
|
bool addClient(int fd);
|
||||||
|
private:
|
||||||
|
void mainFunc();
|
||||||
|
private:
|
||||||
|
std::unordered_map<int, TcpConnection*> m_clients;
|
||||||
|
std::thread m_thread;
|
||||||
|
};
|
||||||
|
|
||||||
|
}
|
49
src/net/tcp/io_thread.cc
Normal file
49
src/net/tcp/io_thread.cc
Normal file
@ -0,0 +1,49 @@
|
|||||||
|
#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;
|
||||||
|
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();
|
||||||
|
}
|
||||||
|
}
|
Loading…
Reference in New Issue
Block a user