栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

c++ 实现一个 函数顺序执行队列

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

c++ 实现一个 函数顺序执行队列

如题 , 什么是函数顺序执行队列 ?

日常开发可能有这样的需求

软件打开 初始化

  1. 先初始化声音模块
  2. 初始化视频模块
  3. 初始化某某模块
    等 顺序执行 ,而且初始化过程还有阻塞等,一个模块错误就退出报错
    如果我们全部顺序写 会有很多重复的代码

比如
if(!initA())
{
dosometh();
exit;
}
if(!initB())
{
dosometh();
exit;
}
if(!initC())
{
dosometh();
exit;
}

可能c 还需要在线程中执行 等等 写起来不方便 不美观

那么我们实现一个这样的队列 , 把函数都封装好 丢进去, 让他执行就好了。

这是一个雏形 用了 20分钟写的
很多功能都没有实现, 基本的函数顺序执行队列完成了

由于函数的参数传递不等 我这里用的是个 void* , 你的参数如果是多个 就放到结构体里面 转为void*

下面是代码 比较精简:

// funcExecQueue.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//

#include 
#include 
#include 

class FuncExecQueue
{
public:
    typedef std::function function_;

    struct FuncStruct
    {
        function_ func = nullptr;
        void* param = nullptr;

        FuncStruct() {}
        FuncStruct(const function_& f, void* p)
            : func(f), param(p) {}
    };

public:
    FuncExecQueue() {}
    ~FuncExecQueue() {}

    void push(const FuncStruct& funcStruct)
    {
        m_funStructQueue.push(funcStruct);
    }

    void run()
    {
        while (false == m_funStructQueue.empty())
        {
            auto funcStruct = m_funStructQueue.front();
            m_funStructQueue.pop();
            if (funcStruct.func)
            {
                funcStruct.func(funcStruct.param);
            }
        }
    }

private:
    
    std::queue m_funStructQueue;
};



void a(void* p)
{
    std::cout << "i am a()" << std::endl;
}

void b(void* p)
{
    std::cout << "i am b()" << std::endl;
}

struct CustomParam
{
    int a = 0;
    int b = 0;
};

void c(void* p)
{
    CustomParam* param = static_cast(p);

    if (param)
    {
        std::cout << "i am c()" << std::endl;
        std::cout << param->a << std::endl;
        std::cout << param->b << std::endl;
        delete param ;
        param  = nullptr;
    }
}




int main()
{
    FuncExecQueue queue;

    queue.push(FuncExecQueue::FuncStruct(&a, nullptr));
    queue.push(FuncExecQueue::FuncStruct(&b, nullptr));

    CustomParam* p = new CustomParam();
    p->a = 100;
    p->b = 500;

    queue.push(FuncExecQueue::FuncStruct(&c, static_cast(p)));
    
    queue.run();

    system("pause");
}


代码很少 咱们来过一下


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/457180.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号