找回密码
 用户注册

QQ登录

只需一步,快速开始

查看: 3786|回复: 4

libuv的一些尝试代码,感觉还可以。

[复制链接]
 楼主| 发表于 2015-11-21 22:28:41 | 显示全部楼层 |阅读模式
#pragma once

typedef boost::function<void()> VoidFunc;
class FuncArray
{
public:
    FuncArray(void)
    {
        funcvec.reserve(4096);
    }

    void post(VoidFunc func)
    {
        asio::detail::mutex::scoped_lock lock(mtx);
        funcvec.push_back(func);
    }

    void handle()
    {
        std::vector<VoidFunc> curfuncvec;
        {
            asio::detail::mutex::scoped_lock lock(mtx);
            curfuncvec.swap(funcvec);
        }
        for(size_t i=0;i<curfuncvec.size();i++)
        {
            curfuncvec[i]();
        }
    }

    ~FuncArray(void){}
    std::vector<VoidFunc> funcvec;
    asio::detail::mutex mtx;
};

#pragma once
#include "funcarray.h"

class UvLoopWorker
{
public:
    UvLoopWorker(void);
    virtual ~UvLoopWorker(void);

    //启动线程
    int start()
    {
        new asio::thread(boost::bind(&UvLoopWorker::run,this));
        return 0;
    }
   
    //在他的线程里面执行一个函数
    void post(VoidFunc func)
    {
        _fa.post(func);
        notify();
    }

    virtual void on_start_loop(){}
   
protected:

    void notify()
    {
        int r = uv_async_send(&_async);
    }

    int run();

    static void async_cb(uv_async_t* handle)
    {
        UvLoopWorker *pthis=(UvLoopWorker *)handle->data;
        pthis->_fa.handle();
    }
    uv_async_t _async;
    uv_loop_t *_loop;
    FuncArray _fa;
};

class UvLoopWorkerMgr
{
public:
    static void init(int numofitems);
    static std::vector<UvLoopWorker *> wrkers;

    void post(VoidFunc &func)
    {
        static int id=0;
        id++;
        post(func,id);
    }

    void post(VoidFunc &func,int idx)
    {
        int nitem=idx % wrkers.size();
        return wrkers[nitem]->post(func);
    }
};

发表于 2015-11-21 22:32:19 | 显示全部楼层
有时间要研究研究这个东西,看你很推崇。
 楼主| 发表于 2015-11-22 20:11:33 | 显示全部楼层
如果不用c++开发网络程序,就不需要。
发表于 2015-12-31 08:44:01 | 显示全部楼层
有点类似工作线程池,对对象数据取摸调用?
 楼主| 发表于 2015-12-31 20:47:46 | 显示全部楼层
是的,工作线程池,跟asio::io_service差不多,但是asio::io_service你每投递一个,他会投递一个请求,这个你如果同时投递几千个,他也只激活一次,
您需要登录后才可以回帖 登录 | 用户注册

本版积分规则

Archiver|手机版|小黑屋|ACE Developer ( 京ICP备06055248号 )

GMT+8, 2024-3-29 07:47 , Processed in 0.019200 second(s), 6 queries , Redis On.

Powered by Discuz! X3.5

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表