gpt4 book ai didi

c++ - PostgreSQL 内存泄漏

转载 作者:塔克拉玛干 更新时间:2023-11-03 07:37:26 26 4
gpt4 key购买 nike

我正在运行一个用 C++ 编写的系统,它不断地将大量数据插入我的数据库,同时查询数据库以获取更新的结果。我的问题是在此过程中启动的 postgres 线程不断使用越来越多的内存。我需要知道如何解决这个问题。以下是演示此问题的更简单的程序。

#include <iostream>
#include <sstream>

#include <tbb/tbb_thread.h>//intel parallel studio class for parel

#include "libpq-fe.h"
#include "libpq/libpq-fs.h"

class Inserter{
public:
void operator()(){
PGconn* conn = PQconnectdb("user=postgres password=1234");
int i=0;
while(1){
std::stringstream insert;
insert << "INSERT INTO tmp (value) VALUES (" << i%250 << ");";
PGresult* res=PQexec(conn,insert.str().c_str());
if (PQresultStatus(res) == PGRES_FATAL_ERROR){
std::cout << "Error in inserting data:\nError code: " << PQresStatus(PQresultStatus(res)) << "Error Message: " << PQerrorMessage(conn);
PQclear(res);
PQfinish(conn);
return;
}
PQclear(res);
i++;
}
}

};
class Queryer{
public:
void operator()(){
PGconn* conn = PQconnectdb("user=postgres password=1234");
int j=0;
while (1){
std::stringstream query;
query << "SELECT * FROM tmp WHERE id>" << j%1000 << ";";
PGresult* res=PQexec(conn,query.str().c_str());
if (PQresultStatus(res) == PGRES_FATAL_ERROR){
std::cout << "Error in searching data:\nError code: " << PQresStatus(PQresultStatus(res)) << "Error Message: " << PQerrorMessage(conn);
PQclear(res);
PQfinish(conn);
return;
}
PQclear(res);
Sleep(10);
j++;
}
}

};

void main(){
//connect to Database
PGconn* conn = PQconnectdb("user=postgres password=1234");

//create table
std::cout << "Creating table...\n";
PGresult* res=PQexec(conn,"CREATE TABLE tmp (id SERIAL8 PRIMARY KEY,value INT);");
if (PQresultStatus(res) == PGRES_FATAL_ERROR){
std::cout << "Error in Creating table:\nError code: " << PQresStatus(PQresultStatus(res)) << "Error Message: " << PQerrorMessage(conn);
//PQclear(res);
//PQfinish(conn);
//return;
}
PQclear(res);
PQfinish(conn);

std::cout << "Starting table filling thread...\n";
//fill table with some data
Inserter ins;
tbb::tbb_thread filling(ins);
Sleep(1000);
// searching table ... here is where the memory leak is
std::cout << "Starting table searching thread...\n";
Queryer que;
tbb::tbb_thread searching(que);

while(true)
{
tbb::tick_count::interval_t t(1.0);
tbb::this_tbb_thread::sleep(t);
}
}

最佳答案

也许您需要以某种方式关闭您的连接?

关于c++ - PostgreSQL 内存泄漏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1280513/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com