一、C语言文章来源:https://www.toymoban.com/news/detail-810248.html
- Channel.h
#pragma once
#include <stdbool.h>
// 定义函数指针
typedef int(*handleFunc)(void* arg);
// 定义文件描述符的读写事件
enum FDEvent {
TimeOut = 0x01,
ReadEvent = 0x02,
WriteEvent = 0x04
};
struct Channel {
// 文件描述符
int fd;
// 事件
int events;
// 回调函数
handleFunc readCallback;// 读回调
handleFunc writeCallback;// 写回调
handleFunc destroyCallback;// 销毁回调
// 回调函数的参数
void* arg;
};
// 初始化一个Channel
struct Channel* channelInit(int fd, int events, handleFunc readFunc, handleFunc writeFunc,handleFunc destroyFunc, void* arg);
// 修改fd的写事件(检测 or 不检测)
void writeEventEnable(struct Channel* channel, bool flag);
// 判断是否需要检测文件描述符的写事件
bool isWriteEventEnable(struct Channel* channel);
- Channel.c
#include "Channel.h"
#include <stdlib.h>
struct Channel* channelInit(int fd, int events, handleFunc readFunc,
handleFunc writeFunc, handleFunc destroyFunc, void* arg) {
struct Channel* channel = (struct Channel*)malloc(sizeof(struct Channel));
channel->fd = fd;
channel->events = events;
channel->readCallback = readFunc;
channel->writeCallback = writeFunc;
channel->destroyCallback = destroyFunc;
channel->arg = arg;
return channel;
}
void writeEventEnable(struct Channel* channel, bool flag) {
if(flag) {
channel->events |= WriteEvent;
}else{
channel->events = channel->events & ~WriteEvent;
}
}
bool isWriteEventEnable(struct Channel* channel) {
return channel->events & WriteEvent;
}
二、C++文章来源地址https://www.toymoban.com/news/detail-810248.html
- Channel.h
#pragma once
#include <stdbool.h>
// 定义函数指针
// typedef int(*handleFunc)(void* arg);
using handleFunc = int(*)(void* arg);
// 定义文件描述符的读写事件 (强类型枚举)
enum class FDEvent {
TimeOut = 0x01,
ReadEvent = 0x02,
WriteEvent = 0x04
};
class Channel
{
public:
Channel(int fd, int events, handleFunc readFunc, handleFunc writeFunc,handleFunc destroyFunc, void* arg);
// 回调函数
handleFunc readCallback;// 读回调
handleFunc writeCallback;// 写回调
handleFunc destroyCallback;// 销毁回调
// 修改fd的写事件(检测 or 不检测)
void writeEventEnable(bool flag);
// 判断是否需要检测文件描述符的写事件
bool isWriteEventEnable();
// 取出私有成员的值
inline int getEvent() {
return m_events;
}
inline int getSocket() {
return m_fd;
}
inline const void* getArg() {
return m_arg;
}
private:
// 文件描述符
int m_fd;
// 事件
int m_events;
// 回调函数的参数
void* m_arg;
};
- Channel.cpp
#include "Channel.h"
#include <stdlib.h>
Channel::Channel(int fd, int events, handleFunc readFunc,
handleFunc writeFunc, handleFunc destroyFunc, void* arg) {
m_fd = fd;
m_events = events;
m_arg = arg;
readCallback = readFunc;
writeCallback = writeFunc;
destroyCallback = destroyFunc;
}
void Channel::writeEventEnable(bool flag) {
if(flag) {
m_events |= static_cast<int>(FDEvent::WriteEvent);
}else{
m_events = m_events & ~static_cast<int>(FDEvent::WriteEvent);
}
}
bool Channel::isWriteEventEnable() {
return m_events & static_cast<int>(FDEvent::WriteEvent);
}
到了这里,关于基于多反应堆的高并发服务器【C/C++/Reactor】(下)重构Channel类的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!