10

实现多线程对队列的读写操作(封装类)

 3 years ago
source link: https://blogread.cn/it/article/897?f=hot1
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
您现在的位置首页 --> 算法 --> 实现多线程对队列的读写操作(封装类)

实现多线程对队列的读写操作(封装类)

浏览:2607次  出处信息
由于之前一个server用到后台线程的功能,所以写了一个线程+队列的通用模型。(代码见文章底的附件)
应用场景:当处理的数据不影响回包,即可以在后台执行。
使用方式:一个(或多个)线程向队列中塞数据,一个(或多个)线程从队列里取数据并执行。
已实现功能:
    1.统计功能。支持添加数据次数,添加溢出次数,执行次数,出错次数。
    2.写错误流水功能。当添加溢出,或执行出错,会打印错误流水号码,入队列时间,等等,格式可以自己控制。
    3.支持继承。可以自由重载想要实现的功能。
使用示例:

#include “thread_base.h”
class CChildThread:public CThreadBase
{
    protected:
        virtual int Process(StructSyncData * oneData,void* args)
        {
            //printf(”%lld\n”,oneData->ID);
            return 0;
        }
        virtual int init(char* cfgFileName)
        {
            m_ThreadNum=100;
            m_BoolWriteBill=true;
            return 0;
        }
        virtual void AfterAddData(long long popID,int iTime,int preRet)
        {
            if(preRet)
            {
                int t_Time=time(NULL);
                WriteBill(“[%lld][%d][%d]\n”,popID,iTime,t_Time);
            }
        }
};
int main()
{
    CChildThread t_thread;
    int ret;
    ret = t_thread.Init(“”);
    if(ret)
    {
        return 0;
    }
    t_thread.Start();
    long long popID=0;
    int i=0;
    while(1)
    {
        StructSyncData *t_data = new StructSyncData();
        t_data->ID=i;
        t_thread.AddData(t_data,popID);
        i++;
    }
}

希望对大家有用~

代码附件下载

觉得文章有用?立即:

和朋友一起 共学习 共进步!

建议继续学习:

QQ技术交流群:445447336,欢迎加入!
扫一扫订阅我的微信号:IT技术博客大学习

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK