c++ - boost::lockfree::queue 似乎没有释放内存,尽管调用了每个集合对象上的析构函数

标签 c++ boost lock-free

这里的问题是,boost::lockfree::queue 在分配内存后不会释放内存。为什么 freelist 节点没有返回给操作系统?调用单个集合对象的析构函数。

我想解决内存问题,关于无锁队列内存分配的任何建议。我在这里做错了什么吗?

#include <iostream>
#include <Windows.h>
#include <boost/thread/thread.hpp>
#include <boost/lockfree/queue.hpp>

using namespace std;
using namespace boost;

struct Record
{
    char str[128];

    Record(const char* rec)
    {
        memset(this->str, 0, sizeof(this->str));
        strcpy_s(this->str, rec);
    }

    ~Record()
    {
        cout << "~Record " << this->str << endl;
    }

    Record& operator= (const Record& rec)
    {
        if (this == &rec)
        {
            return *this;
        }

        memset(this->str, 0, sizeof(this->str));
        strcpy_s(this->str, rec.str);
        return *this;
    }
};

typedef boost::lockfree::queue<Record*, boost::lockfree::fixed_sized<true>> RecordsQueue;

RecordsQueue Records(10000);

class MyClass
{
public:

    void FillThread()
    {
        int i = 0;
        while (true)
        {
            Record *rec = new Record(to_string(i).c_str());
            Records.push(rec);
            i++;
        };
    }

    void ProcessThread()
    {
        while (true)
        {
            Record *rec;
            Records.pop(rec);
            {
                cout << "Record " << rec->str << endl;
                delete rec;
            }
        };
    }
};

int _tmain(int argc, _TCHAR* argv[])
{
    boost::thread* thread1, *thread2;

    MyClass myObj;

    thread1 = new boost::thread(boost::bind(&MyClass::FillThread, myObj));
    HANDLE threadHandle1 = thread1->native_handle();
    SetThreadPriority(threadHandle1, THREAD_PRIORITY_NORMAL);

    boost::this_thread::sleep(boost::posix_time::seconds(1));

    thread2 = new boost::thread(boost::bind(&MyClass::ProcessThread, myObj));
    HANDLE threadHandle2 = thread2->native_handle();
    SetThreadPriority(threadHandle2, THREAD_PRIORITY_NORMAL);

    thread1->join();
    thread2->join();

    return 0;
}

最佳答案

看起来您向队列中推送的记录多于可用空间。这会覆盖以前拥有的空间,并导致它们将来不会被释放。尝试将 FillThread 更改为 for 循环。

关于c++ - boost::lockfree::queue 似乎没有释放内存,尽管调用了每个集合对象上的析构函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26672692/

相关文章:

c++ - fedora 21 上的 gcc-c++-4.1.2(双)安装

c++ - Boost w/C++ - 奇怪的互斥行为

c++ - 我不明白为什么 boost::asio::read_until 读取定界符后面的字符

multithreading - 使用 boost::lockfree::spsc_queue 时需要内存屏障吗?

c++ - Boost.lockfree 在 RHEL 5.3 上的性能

c++ - 如何使用 fopen 和文件指针打开多个文件?

c++ - 进程外 COM 服务器中的 MessageBox

c++ - 从具有 O(1) 运行时间的 vector 中删除元素

c++ - 更好地处理 boost::program_options 中丢失/错误的键

concurrency - 通过使用无锁算法,Clojure是否无锁?