zl程序教程

您现在的位置是:首页 >  后端

当前栏目

【C++】详解 eventpp 事件调度程序和回调列表库

C++事件列表程序 详解 调度 回调
2023-09-14 09:14:31 时间

目录

1、eventpp 事件调度程序和回调列表库

2、特点

3、程序示例

使用回调列表

事件调度器 

 使用事件队列


1、eventpp 事件调度程序和回调列表库

eventpp 是一个用于回调、事件调度程序和事件队列的C++事件库。使用 eventpp,您可以轻松实现信号和插槽机制、发布者和订阅者模式或观察者模式。

wqking/eventpp:事件调度程序和C++回调列表 (github.com)icon-default.png?t=M85Bhttps://github.com/wqking/eventpp

2、特点

  • 支持同步事件调度和异步事件队列。
  • 可通过策略和混合进行配置和扩展。
  • 支持通过混音进行事件过滤器。
  • 支持嵌套事件。在处理事件的过程中,侦听器可以安全地调度事件并附加/预置/插入/删除其他侦听器。
  • 线程安全。支持多线程。
  • 异常安全。大多数操作都保证了强大的异常安全性。
  • 经过良好测试。由单元测试提供支持。
  • 事件队列可以在 1 秒内处理 10M 个事件(每毫秒 10K 个事件)。
  • 回调列表可以在 1 秒内调用 100M 次回调(每毫秒 100K 次回调)。
  • 回调列表可以在 1 秒内添加/删除 5M 个回调(每毫秒 5K 个回调)。
  • 侦听器和事件可以是任何类型的,不需要从任何基类继承。
  • 可以简化使用的实用程序,例如自动断开连接、单次侦听器、参数类型适配器等。
  • 仅标头,无源文件,无需构建。不依赖于其他库。
  • 需要 C++ 11。
  • 用便携式和标准C++编写

直接将源代码包含在项目中。

Eventpp 是仅标头库。只需克隆源代码,然后将 eventpp 中的“include”文件夹添加到您的项目包含目录中,然后您就可以使用该库。您无需链接到任何源代码。

3、程序示例

使用回调列表

#include <iostream>
#include "eventpp/callbacklist.h"

using namespace std;

int main()
{
    eventpp::CallbackList<void (const string &, const bool)> callbackList;

    callbackList.append([](const string & s, const bool b) {
        cout << boolalpha << "s:" << s << "b:" << b << endl;
    });

    callbackList.append([](string s, int b) {
        std::cout << std::boolalpha << "Got callback 2, s is " << s << " b is " << b << std::endl;
    });

    callbackList("fan", true);

    return 0;
}

事件调度器 

#include "eventpp/eventdispatcher.h"
static void test() {
    cout << "test" << endl;
}

void CFan::test_2() {
    eventpp::EventDispatcher<int, void()> dispatcher;
    dispatcher.appendListener(3, []() {
        cout << "get 3" << endl;
    });

    dispatcher.appendListener(6, [](){
        cout << "get 6(1)" << endl;
    });

    dispatcher.appendListener(6, []() {
        cout << "get 6(2)" << endl;
    });

    dispatcher.appendListener(8, test);

    // dispatch
    dispatcher.dispatch(8);

    dispatcher.dispatch(3);

    dispatcher.dispatch(6);
}

 使用事件队列

#include "eventpp/eventqueue.h"
static void task_1(const string & arg1, const string & arg2) {
    cout << arg1 << "+" << arg2 << endl;
}

static void task_2(const string &arg1, const string & arg2) {
    cout << arg1 << "+" << arg2 << endl;
}

void CFan::test_3() {
    eventpp::EventQueue<int, void (const string &, const string &)> queue;
    queue.appendListener(1, task_1);
    queue.appendListener(5, task_2);

    queue.enqueue(1, "Hello", "world!");
    queue.enqueue(5, "Fan", "1111");
    queue.process();
}