与C ++中的传统新删除方法相比,线程安全内存池没有提供更好的性能,为什么?

时间:2019-05-28 05:32:37

标签: c++ multithreading performance memory-management low-latency

我已经实现了mempool,如果在这种情况下它不是线程安全的,则可以得到更好的结果,几乎是传统new的1/3,请删除,但是一旦我使其成为线程安全,它的性能就会比传统new慢,删除。

Mempool.cpp

    template<typename T>
class Mempool {
private:

    std::atomic<int> totalSize;
//  int totalSize; // without thread safe
    T **head;
//  int allocPos; // without thread safe
    std::atomic<int> allocPos;
    void initialize() {

        head = (T **) calloc(totalSize, sizeof(T *));
        for (int i = allocPos; i < totalSize; i++) {
            head[i] = (T*) calloc(1, sizeof(T));
        }
    }

    void expand() {
        totalSize += totalSize;
        head = (T**) realloc(head, sizeof(T*) * totalSize);
        for (int i = allocPos; i < totalSize; i++) { // As data till allocPos is already allocated
            head[i] = (T*) calloc(1, sizeof(T));
        }
    }
public:
    Mempool(int size) :
            totalSize(size), head(nullptr), allocPos(0) {
        initialize();
    }
    T* alloc() {
        if (allocPos >= totalSize)
            expand();
        T* temp = head[allocPos++];
        return temp;
    }
    void dealloc(T *f_node) {
        head[--allocPos] = f_node;
    }
    ~Mempool() {
        for (int i = allocPos; i < totalSize; i++) { // As data till allocPos is already allocated
            free(head[i]);
        }
        free(head);
    }
};

class Variable {
public:
    int a;
    int b;
    long c;
    int d;
    int e;
    long f;
    double g;
        char h;
    };

Mempool<Variable> varpool(200);
int main() {
    const int testSize = 200;
    std::string c("Case1");
    Timer t1(c);
    t1.start();
    Variable *var1[testSize];
    for (int j = 0; j < 30; ++j) {
        for (int i = 0; i < testSize; ++i)
            var1[i] = varpool.alloc();
        for (int i = 0; i < testSize; ++i)
            varpool.dealloc(var1[i]);
    }
    t1.stop();
    c = "Case2";
    Timer t2(c);
    t2.start();
    Variable *var2[testSize];
    for (int j = 0; j < 30; ++j) {
        for (int i = 0; i < testSize; ++i)
            var2[i] = new Variable();
        for (int i = 0; i < testSize; ++i)
            delete var2[i];
    }

    t2.stop();
    return 0;
}

这里的计时器显示了在线程安全实现期间case1的更多时间。我认为应该减少一些,请提供实现过程中我应该做些什么更改。

OS:Linux Centos 7,64位4核。

0 个答案:

没有答案