微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

pqxx::nontransaction 似乎开始交易

如何解决pqxx::nontransaction 似乎开始交易

基本问题: 我有一个 SELECT 语句,其中包含大量的 bytea 比较,这需要大量时间来处理,我需要减少这种情况。 为了减少我在 std::thread 中使用多线程的时间。

为了确保在生成多个事务时不会遇到问题,并且 SELECT 是线程安全的,我使用了 pqxx::nontransaction

我收到此错误libc++abi: libc++abi: terminating with uncaught exception of type pqxx::usage_error: Started new transaction while transaction was still active.terminating with uncaught exception of type pqxx::usage_error: Started new transaction while transaction was still active.

这里使用 std::string 作为指纹的表示来说明基本思想。

#include <pqxx/pqxx>
#include <string>

#include <vector>
#include <string>

#include <thread>

int main(void)
{
    pqxx::connection con; // Assum setup
    std::vector<std::string> items; /// Assume containing content

    std::vector<std::thread> threads;

    size_t num_items_thread = items.size() / std::thread::hardware_concurrency() - 1;
    size_t items_remainder = items.size() % (std::thread::hardware_concurrency() - 1);

    size_t off = 0; 
    
    for (size_t i = 0; i < std::thread::hardware_concurrency() - 1; ++i)
    {
        size_t end = off + num_items_thread;
        if (i == std::thread::hardware_concurrency() - 2)
        {
            end = items.size();
        }
        
        threads.emplace_back([&items,&con,off,end](){
                                 pqxx::nontransaction work(con);

                                 std::vector<std::string> data(std::begin(items) + off,std::begin(items) + end);

                                 std::string param_list = "";

                                 for (size_t i = 1; i <= data.size(); ++i)
                                 {

                                     param_list = param_list + std::to_string(i) + ","; 
                                 }
                                 param_list = param_list.substr(0,param_list.size() - 1);
                                 std::string query = "SELECT * FROM tbl WHERE arr IN (" + param_list + ")";
                                 work.exec_params(query,pqxx::prepare::make_dynamic_params(data));
                                 
                             });

        off = off + num_items_thread;
    }

    for (auto& thread : threads)
    {
        thread.join();
    }
    return 0; 
}

根据我对 libpqxx 文档的理解,这应该可以让我在不调用事务的情况下执行,但基于错误,我仍然得到一个事务。 我怎样才能避免这种情况?

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。