在C++11中實現Nginx中的記憶體池

来源:https://www.cnblogs.com/woden3702/archive/2022/05/29/16325025.html
-Advertisement-
Play Games

前言 還記得你第一次遇到「線程安全」這個詞的時候嗎? 我第一次遇到線程安全這個詞是在學習多線程併發操作的時候,看到人家文章里出現這個詞,還有說各種線程安全的類,但是一開始並不理解線程安全是什麼意思,也沒去深究線程怎樣是安全的?怎樣是不安全的?只是腦子裡接收了這麼一個詞。 線程安全是多線程編程時的計算 ...


將Nginx中的記憶體池實現移植到c++,通過面向對象的方式實現

頭文件:

//
// Created by 26685 on 2022-05-29 19:57.
// Description:NginxMemoryPool.h
//

#ifndef MEMORYPOOL_NGINXMEMORYPOOL_H
#define MEMORYPOOL_NGINXMEMORYPOOL_H

#include<cstdlib>
#include<cstdio>
#include<memory.h>


using u_char = unsigned char;
using ngx_uint_t = unsigned int;
using ngx_pool_cleanup_pt = void (*)(void *data);//函數指針ngx_pool_cleanup_pt

struct ngx_pool_s;

//清除節點
struct ngx_pool_cleanup_s {
    ngx_pool_cleanup_pt handler;//回調函數
    void *data;//上面函數中使用的數據
    ngx_pool_cleanup_s *next;
};

//指向下一個大尺寸pool的節點
struct ngx_pool_large_s {
    ngx_pool_large_s *next;//next指針,指向下一個節點
    void *alloc;//堆記憶體地址(大塊記憶體地址)
};

//指向下一個小尺寸pool頭結點的結構
struct ngx_pool_data_s {
    u_char *last;
    u_char *end;
    ngx_pool_s *next;
    ngx_uint_t failed;
};

//記憶體池的頭文件
struct ngx_pool_s {
    ngx_pool_data_s d;
    size_t max;
    ngx_pool_s *current;
    ngx_pool_large_s *large;
    ngx_pool_cleanup_s *cleanup;
};
//將p調整為a的倍數
#define ngx_align_ptr(p, a)                                                   \
    (u_char *) (((uintptr_t) (p) + ((uintptr_t) a - 1)) & ~((uintptr_t) a - 1))
//將d調整為a的倍數
#define ngx_align(d, a)     (((d) + (a - 1)) & ~(a - 1))

//將記憶體塊設置為0
#define ngx_memzero(buf, n)       (void) memset(buf, 0, n)

#define  NGX_OK          0
#define  NGX_ERROR      -1
#define  NGX_AGAIN      -2
#define  NGX_BUSY       -3
#define  NGX_DONE       -4
#define  NGX_DECLINED   -5
#define  NGX_ABORT      -6

const int NGX_ALIGNMENT = sizeof(unsigned long);//對齊長度

const int ngx_pagesize = 4096;//最大頁面大小4k

const int NGX_MAX_ALLOC_FROM_POOL = ngx_pagesize - 1;//最大小記憶體池

const int NGX_DEFAULT_POOL_SIZE = 16 * 1024;//

const int NGX_POOL_ALIGNMENT = 16;


const int NGX_MIN_POOL_SIZE = ngx_align((sizeof(ngx_pool_s) + 2 * sizeof(ngx_pool_large_s)), \
              NGX_POOL_ALIGNMENT);


class NginxMemoryPool {
public:

    explicit NginxMemoryPool(size_t size = 512);

    ~NginxMemoryPool() {
        printf("destroy pool! \n");
        ngx_destroy_pool();
    }

    void *ngx_create_pool(size_t size);

    void ngx_destroy_pool();

    void ngx_reset_pool();

    //考慮記憶體對齊,從記憶體池申請size大小的記憶體
    void *ngx_palloc(size_t size);

    //不考慮記憶體對齊
    void *ngx_pnalloc(size_t size);

    void *ngx_pcalloc(size_t size);

    //添加回調清理操作函數
    ngx_pool_cleanup_s *ngx_pool_cleanup_add(size_t size);

    //釋放大塊記憶體
    int ngx_pfree(void *p);

private:
    ngx_pool_s *pool{};

    void *ngx_palloc_small(size_t size, ngx_uint_t align);

    void *ngx_palloc_block(size_t size);

    void *ngx_palloc_large(size_t size);
};


#endif //MEMORYPOOL_NGINXMEMORYPOOL_H

.cpp實現

//
// Created by 26685 on 2022-05-29 19:57.
// Description:NginxMemoryPool.cpp
//

#include "include/NginxMemoryPool.h"

ngx_pool_cleanup_s *NginxMemoryPool::ngx_pool_cleanup_add(size_t size) {
    ngx_pool_cleanup_s *c;

    c = (ngx_pool_cleanup_s *) ngx_palloc(sizeof(ngx_pool_cleanup_s));
    if (c == nullptr) {
        return nullptr;
    }

    if (size) {
        c->data = ngx_palloc(size);
        if (c->data == nullptr) {
            return nullptr;
        }

    } else {
        c->data = nullptr;
    }

    c->handler = nullptr;
    c->next = pool->cleanup;

    pool->cleanup = c;


    return c;
}

void *NginxMemoryPool::ngx_create_pool(size_t size) {
    ngx_pool_s *p;

    p = (ngx_pool_s *) malloc(size);//按照16位元組對齊
    if (p == nullptr) {
        return nullptr;
    }

    p->d.last = (u_char *) p + sizeof(ngx_pool_s);
    p->d.end = (u_char *) p + size;
    p->d.next = nullptr;
    p->d.failed = 0;

    size = size - sizeof(ngx_pool_s);
    p->max = (size < NGX_MAX_ALLOC_FROM_POOL) ? size : NGX_MAX_ALLOC_FROM_POOL;

    p->current = p;
    p->large = nullptr;
    p->cleanup = nullptr;

    pool = p;
    return p;
}

void NginxMemoryPool::ngx_destroy_pool() {
    ngx_pool_s *p, *n;
    ngx_pool_large_s *l;
    ngx_pool_cleanup_s *c;

    //現根據記憶體池中的cleanup保存的信息把大塊記憶體中指向的外部資源釋放掉
    for (c = pool->cleanup; c; c = c->next) {
        if (c->handler) {
            c->handler(c->data);
        }
    }

    //清理掉外部資源後將大塊記憶體釋放掉
    for (l = pool->large; l; l = l->next) {//遍歷每一個large記憶體
        if (l->alloc) {
            free(l->alloc);
        }
    }

    for (p = pool, n = pool->d.next; /* void */; p = n, n = n->d.next) {
        free(p);

        if (n == nullptr) {
            break;
        }
    }
}

void NginxMemoryPool::ngx_reset_pool() {
    ngx_pool_s *p;
    ngx_pool_large_s *l;

    for (l = pool->large; l; l = l->next) {
        if (l->alloc) {
            free(l->alloc);
        }
    }

    //第一塊記憶體的頭是sizeof(ngx_pool_s)
    p->d.last = (u_char *) p + sizeof(ngx_pool_s);
    p->d.failed = 0;
    //後面記憶體塊的頭的大小是sizeof(ngx_pool_data_s)
    for (p = pool->d.next; p; p = p->d.next) {
        p->d.last = (u_char *) p + sizeof(ngx_pool_data_s);
        p->d.failed = 0;
    }

    pool->current = pool;
    pool->large = nullptr;
}

void *NginxMemoryPool::ngx_palloc(size_t size) {
    if (size <= pool->max) {
        return ngx_palloc_small(size, 1);
    }
    return ngx_palloc_large(size);
}

void *NginxMemoryPool::ngx_pnalloc(size_t size) {
    if (size <= pool->max) {
        return ngx_palloc_small(size, 0);
    }
    return ngx_palloc_large(size);
}

void *NginxMemoryPool::ngx_pcalloc(size_t size) {
    void *p;

    p = ngx_palloc(size);
    if (p) {
        ngx_memzero(p, size);
    }

    return p;
}

int NginxMemoryPool::ngx_pfree(void *p) {
    ngx_pool_large_s *l;

    for (l = pool->large; l; l = l->next) {
        if (p == l->alloc) {
            free(l->alloc);
            l->alloc = nullptr;

            return NGX_OK;
        }
    }
    return NGX_DECLINED;
}

void *NginxMemoryPool::ngx_palloc_small(size_t size, ngx_uint_t align) {
    u_char *m;
    ngx_pool_s *p;

    p = pool->current;

    do {
        m = p->d.last;

        if (align) {
            m = ngx_align_ptr(m, NGX_ALIGNMENT);
        }

        if ((size_t) (p->d.end - m) >= size) {
            p->d.last = m + size;

            return m;
        }

        p = p->d.next;

    } while (p);

    return ngx_palloc_block(size);
}

void *NginxMemoryPool::ngx_palloc_block(size_t size) {
    u_char *m;
    size_t psize;
    ngx_pool_s *p, *newMem;

    psize = (size_t) (pool->d.end - (u_char *) pool);

    m = (u_char *) malloc(psize);
    if (m == nullptr) {
        return nullptr;
    }

    newMem = (ngx_pool_s *) m;

    newMem->d.end = m + psize;
    newMem->d.next = nullptr;
    newMem->d.failed = 0;

    m += sizeof(ngx_pool_data_s);
    m = ngx_align_ptr(m, NGX_ALIGNMENT);
    newMem->d.last = m + size;

    for (p = pool->current; p->d.next; p = p->d.next) {
        if (p->d.failed++ > 4) {
            pool->current = p->d.next;
        }
    }

    p->d.next = newMem;

    return m;
}

void *NginxMemoryPool::ngx_palloc_large(size_t size) {
    void *p;
    ngx_uint_t n;
    ngx_pool_large_s *large;

    p = malloc(size);
    if (p == nullptr) {
        return nullptr;
    }

    n = 0;

    for (large = pool->large; large; large = large->next) {
        if (large->alloc == nullptr) {
            large->alloc = p;
            return p;
        }

        if (n++ > 3) {
            break;
        }
    }

    large = (ngx_pool_large_s *) ngx_palloc_small(sizeof(ngx_pool_large_s), 1);//在小塊池中建立large記憶體塊
    if (large == nullptr) {
        free(p);
        return nullptr;
    }
    large->alloc = p;
    large->next = pool->large;
    pool->large = large;

    return p;
}

NginxMemoryPool::NginxMemoryPool(size_t size) {
    printf("%d\n", size);
    ngx_create_pool(size);
}

測試代碼:

#include <iostream>
#include <cstring>
#include "include/NginxMemoryPool.h"


typedef struct Data stData;
struct Data {
    char *ptr;
    FILE *pfile;
};

void func1(void *p1) {
    char *p = (char *) p1;
    printf("free ptr mem!\n");
    free(p);
}

void func2(void *pf1) {
    FILE *pf = (FILE *) pf1;
    printf("close file!\n");
    fclose(pf);
}

int main() {
    NginxMemoryPool pool;

    // 512 - sizeof(ngx_pool_t) - 4095   =>   max
    //pool.ngx_create_pool(512);


    void *p1 = pool.ngx_palloc(128); // 從小塊記憶體池分配的
    if (p1 == nullptr) {
        printf("ngx_palloc 128 bytes fail...");
        return -1;
    }

    stData *p2 = (stData *) pool.ngx_palloc(512); // 從大塊記憶體池分配的
    if (p2 == nullptr) {
        printf("ngx_palloc 512 bytes fail...");
        return -1;
    }
    p2->ptr = (char *) malloc(12);
    strcpy(p2->ptr, "hello world\n");
    p2->pfile = fopen("data.txt", "w");

    ngx_pool_cleanup_s *c1 = pool.ngx_pool_cleanup_add(sizeof(char *));
    c1->handler = func1;
    c1->data = p2->ptr;

    ngx_pool_cleanup_s *c2 = pool.ngx_pool_cleanup_add(sizeof(FILE *));
    c2->handler = func2;
    c2->data = p2->pfile;

    //pool.ngx_destroy_pool(); // 1.調用所有的預置的清理函數 2.釋放大塊記憶體 3.釋放小塊記憶體池所有記憶體

    return 1;
}

您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • 事務 事務的四個ACID特性。 Atomicity 原子性 Consistency 一致性 Isolation 隔離性 Durability 持久性 原子性 原子性即這個事務的任務要麼全做了,要麼全部沒做,不能出現做一半這種情況。 一致性 一致性即資料庫中的數據必須滿足數據滿足資料庫的約束。 隔離性 ...
  • 主要記錄工作中用到的一些開發語言以及Sql 模板,持續更新 1.Sql相關 1.常用Sql模板 1.1. 可重覆執行視圖 IF EXISTS ( SELECT *FROM sysobjects WHERE id = OBJECT_ID('v_Employee') AND type = 'V' ) D ...
  • 下表數據,是歷時四年,不定期記錄下的本博積分與排名情況。 咋一看,是個挺簡單的數據表,似乎依此可以輕鬆地搞出個增長曲線圖之類的東東,再分析點什麼結論出來。但再仔細研究一下,發現不那麼回事,這裡面還是挺複雜的。 突然有種感覺,這和軟體開發何期的相似。有多少次,剛聽到一個新需求時,會感覺這不是個什麼事, ...
  • 緊急更新第二彈,然後就剩下最後一彈,也就是整個前臺的項目 一.購物車 1.加入購物車(新知識點) 加入到購物車是需要介面操作的,因為我們需要將用戶的加入到購物車的保存到伺服器資料庫,你的賬號後面才會在你自己的購物車看到,所以這裡要先寫介面 然後vuex三部曲, 返回來的數據沒有data,就是告訴你成 ...
  • jQuery jQuery是什麼 jQuery是一個快速、簡潔的JavaScript框架,是繼Prototype之後又一個優秀的JavaScript代碼庫(或JavaScript框架)。jQuery設計的宗旨是“write Less,Do More”,即倡導寫更少的代碼,做更多的事情。它封裝Java ...
  • 這幾天一直都在做項目,只是沒有上傳上來,即將把前臺項目完結了。現在開始更新整個前臺的部分 一.麵包屑處理 1.分類操作 點擊三級聯動進入搜索產生麵包屑,直接取參數中的name即可 點擊x怎麼幹掉這個麵包屑,直接讓其v-if為這個name,如果點擊x就把name清空 清空還沒完,清空應該再發一次請求, ...
  • 本章是系列文章的第五章,介紹了指針分析方法。指針分析在C/C++語言中非常重要,分析的結果可以有效提升指針的優化效率。 本文中的所有內容來自學習DCC888的學習筆記或者自己理解的整理,如需轉載請註明出處。周榮華@燧原科技 5.1 概念 指針是許多重要編程語言的特性之一 指針的使用,可以避免大量的數 ...
  • 第四章: 設計與聲明 ###18. 讓介面更容易被正確使用,不易被誤用 將你的class的public介面設計的符合class所扮演的角色,必要時不僅對傳參類型限制,還對傳參的值域進一步限制。 ###19. 設計class猶如設計type 內置類型如int、float等,本質也是一個class,用戶 ...
一周排行
    -Advertisement-
    Play Games
  • 移動開發(一):使用.NET MAUI開發第一個安卓APP 對於工作多年的C#程式員來說,近來想嘗試開發一款安卓APP,考慮了很久最終選擇使用.NET MAUI這個微軟官方的框架來嘗試體驗開發安卓APP,畢竟是使用Visual Studio開發工具,使用起來也比較的順手,結合微軟官方的教程進行了安卓 ...
  • 前言 QuestPDF 是一個開源 .NET 庫,用於生成 PDF 文檔。使用了C# Fluent API方式可簡化開發、減少錯誤並提高工作效率。利用它可以輕鬆生成 PDF 報告、發票、導出文件等。 項目介紹 QuestPDF 是一個革命性的開源 .NET 庫,它徹底改變了我們生成 PDF 文檔的方 ...
  • 項目地址 項目後端地址: https://github.com/ZyPLJ/ZYTteeHole 項目前端頁面地址: ZyPLJ/TreeHoleVue (github.com) https://github.com/ZyPLJ/TreeHoleVue 目前項目測試訪問地址: http://tree ...
  • 話不多說,直接開乾 一.下載 1.官方鏈接下載: https://www.microsoft.com/zh-cn/sql-server/sql-server-downloads 2.在下載目錄中找到下麵這個小的安裝包 SQL2022-SSEI-Dev.exe,運行開始下載SQL server; 二. ...
  • 前言 隨著物聯網(IoT)技術的迅猛發展,MQTT(消息隊列遙測傳輸)協議憑藉其輕量級和高效性,已成為眾多物聯網應用的首選通信標準。 MQTTnet 作為一個高性能的 .NET 開源庫,為 .NET 平臺上的 MQTT 客戶端與伺服器開發提供了強大的支持。 本文將全面介紹 MQTTnet 的核心功能 ...
  • Serilog支持多種接收器用於日誌存儲,增強器用於添加屬性,LogContext管理動態屬性,支持多種輸出格式包括純文本、JSON及ExpressionTemplate。還提供了自定義格式化選項,適用於不同需求。 ...
  • 目錄簡介獲取 HTML 文檔解析 HTML 文檔測試參考文章 簡介 動態內容網站使用 JavaScript 腳本動態檢索和渲染數據,爬取信息時需要模擬瀏覽器行為,否則獲取到的源碼基本是空的。 本文使用的爬取步驟如下: 使用 Selenium 獲取渲染後的 HTML 文檔 使用 HtmlAgility ...
  • 1.前言 什麼是熱更新 游戲或者軟體更新時,無需重新下載客戶端進行安裝,而是在應用程式啟動的情況下,在內部進行資源或者代碼更新 Unity目前常用熱更新解決方案 HybridCLR,Xlua,ILRuntime等 Unity目前常用資源管理解決方案 AssetBundles,Addressable, ...
  • 本文章主要是在C# ASP.NET Core Web API框架實現向手機發送驗證碼簡訊功能。這裡我選擇是一個互億無線簡訊驗證碼平臺,其實像阿裡雲,騰訊雲上面也可以。 首先我們先去 互億無線 https://www.ihuyi.com/api/sms.html 去註冊一個賬號 註冊完成賬號後,它會送 ...
  • 通過以下方式可以高效,並保證數據同步的可靠性 1.API設計 使用RESTful設計,確保API端點明確,並使用適當的HTTP方法(如POST用於創建,PUT用於更新)。 設計清晰的請求和響應模型,以確保客戶端能夠理解預期格式。 2.數據驗證 在伺服器端進行嚴格的數據驗證,確保接收到的數據符合預期格 ...