Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux 程式設計 >> Linux 程式設計

Linux C++ 循環緩衝區模板類實作

概述

高頻讀寫大量資料時,循環緩衝區是常用結構。它有一個誘人之處:在生產者與消費者各只有一個的前提下,可以實現免鎖,從而避開鎖競爭帶來的效能損耗;一旦生產者或消費者不止一個,仍舊需要加鎖保護。

核心思路

演算法用「讀游標 + 寫游標 + 掩碼」三者支撐。初始化時傳入一個指數 exp,容量取 2 的 exp 次方,掩碼為容量減一。由於容量是 2 的冪,取模運算可以用位與代替——x & mask 等價於 x % size,而位運算效率更高。寫入位置為 write & mask,讀取位置為 read & mask,游標單向遞增,靠掩碼自然回繞。

實現代碼

// CRecycleQueue.h
#include <iostream>

// 循環緩衝區類模板
template<class T>
class CRecycleQueue {
    private:
        // 循環緩衝區地址指針
        T **_queue;
        // 讀游標(讀的位置)
        int _read;
        // 寫游標(寫的位置)
        int _write;
        // 循環緩衝區的大小
        int _size;
        // 掩碼,用來做位 & 運算,從而實現循環緩衝
        int _mask;

    public:
        CRecycleQueue() {
            _queue = NULL;
            _read = 0;
            _write = 0;
            _size = 0;
            _mask = 0;
        }

        // 初始化循環緩衝區
        bool InitRecycleQueue(int exp) {
            if (0 > exp) {
                return false;
            }
            _read = 0;
            _write = 0;
            // 傳入指數,對 1 做位移:exp = 4 時 _size = 10000b = 16
            _size = 1 << exp;
            // _mask = 01111b = 15
            _mask = _size - 1;
            // 分配緩衝區空間
            _queue = (T **) new char[sizeof(T *) * _size];
            if (NULL == _queue) {
                return false;
            }
            return true;
        }

        /*
         * size = 1000  mask = 0111
         * write 或 read 與 mask 做 & 運算,即可實現循環
         * 之所以不用 % 運算,是因為 & 的效率更高
         *
         * Push:
         *   write = 0;  0000 & 0111 = 0; write++  (寫入第 0 位)
         *   write = 1;  0001 & 0111 = 1; write++  (寫入第 1 位)
         *   ...
         *   write = 8;  1000 & 0111 = 0; write++  (回繞到第 0 位)
         * Pop 同理
         */

        bool Push(T *type) {
            if (NULL == type) {
                return false;
            }
            // 條件不滿足說明緩衝區已滿,Push 進來的資料會丟失
            if (_write < _read + _size) {
                // 存入的是 type 指針,它指向分配的內存空間或類
                _queue[_write & _mask] = type;
                _write++;
                return true;
            }
            return false;
        }

        T *Pop() {
            T *tmp = NULL;
            // 條件不滿足說明緩衝區已無資料
            if (_read < _write) {
                tmp = _queue[_read & _mask];
                _read++;
            }
            return tmp;
        }

        int GetRemainSize() {
            return (_write - _read);
        }
};

測試代碼

// main.cpp
#include <iostream>
#include <pthread.h>
#include "CRecycleQueue.h"
using namespace std;

class UserInfo {
    private:
        int _num;

    public:
        UserInfo(int num) {
            _num = num;
        }

        int getUserNum() {
            return _num;
        }
};

CRecycleQueue<UserInfo> *queue = new CRecycleQueue<UserInfo>;

void *write_func(void *args) {
    int num = 0;
    while (1) {
        // UserInfo 裡可以封裝自定義資料,這裡僅作簡單測試
        UserInfo *info = new UserInfo(num++);
        if (!queue->Push(info)) {
            // Push 失敗,需釋放手動分配的內存
            delete info;
        }
        sleep(1);
    }
}

void *read_func(void *args) {
    while (1) {
        UserInfo *info = NULL;
        if (info = queue->Pop()) {
            cout << info->getUserNum() << endl;
            delete info;
        }
        sleep(1);
    }
}

int main() {
    queue->InitRecycleQueue(8);

    pthread_t pid1;
    pthread_t pid2;
    // 生產者與消費者各一個,此時循環緩衝區免鎖,顯著提升處理效率
    pthread_create(&pid1, NULL, read_func, NULL);
    pthread_create(&pid2, NULL, write_func, NULL);

    pthread_join(pid1, NULL);
    pthread_join(pid2, NULL);
    return 0;
}

編譯:

g++ main.cpp -lpthread -o test

這份實作只覆蓋了核心操作,諸如批量讀寫、剩餘容量精確判空判滿等仍可擴充。使用時特別要注意兩點:一是容量必須是 2 的冪,否則掩碼法失效;二是 Push 進去的是指標,記憶體的所有權與釋放責任由呼叫方承擔,緩衝區只負責轉交,示例中讀取端 delete 完畢才算閉環。

Copyright © Linux教程網 All Rights Reserved