Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

关于httprequest.cpp连接池的使用 #106

Open
GREENHSND opened this issue May 1, 2024 · 2 comments
Open

关于httprequest.cpp连接池的使用 #106

GREENHSND opened this issue May 1, 2024 · 2 comments

Comments

@GREENHSND
Copy link

MYSQL* sql = nullptr;
SqlConnRAII(&sql, SqlConnPool::Instance());
这种声明临时变量的方法明显错误,执行完该句之后就执行析构函数了

@wangerforcs
Copy link

MYSQL* sql = nullptr; SqlConnRAII(&sql, SqlConnPool::Instance()); 这种声明临时变量的方法明显错误,执行完该句之后就执行析构函数了

应该是这样吗?
SqlConnRAII(&sql, SqlConnPool::Instance());改成创建具名对象SqlConnRAII raii(&sql, SqlConnPool::Instance());的形式,然后删去后面手动释放的SqlConnPool::Instance()->FreeConn(sql);

@GREENHSND
Copy link
Author

这样也可以吧,但是不用手动释放吧,RAII这个类的析构函数会释放,另外也可以把RAII这个类删了,在连接池获取连接的接口返回智能指针也可以

std::shared_ptr<MYSQL> SqlConnPool::GetConn() {
    std::shared_ptr<MYSQL> sql_conn;

    std::unique_lock<std::mutex> locker(mtx_);
    if (connQue_.empty()) {
        LOG_WARN("SqlConnPool busy");
        return nullptr;
    }

    MYSQL* sql = connQue_.front();
    connQue_.pop();

    sql_conn.reset(sql, [this](MYSQL* conn) {
        std::lock_guard<std::mutex> locker(mtx_);
        connQue_.push(conn);
        sem_post(&semId_);
    });

    return sql_conn;
}

可以参考一下

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants