一个C++应用程序无法在linux上的一个线程中打开2个SQLite数据库?

Rel*_*lla 1 c++ database linux sqlite

我实际上似乎有这个问题(仅在linux上,这里描述的堆栈跟踪就像

==11682==    at 0x0: ??? // Here goes the error=(
==11682==    by 0x4D49BE: sqlite3_free (sqlite3.c:18155)
==11682==    by 0x102242D5: sqlite3OsInit (sqlite3.c:14162)
==11682==    by 0x1029EB28: sqlite3_initialize (sqlite3.c:107299)
==11682==    by 0x102A159F: openDatabase (sqlite3.c:108909)
==11682==    by 0x102A1B29: sqlite3_open (sqlite3.c:109156)
==11682==    by 0x1021CAB0: sqlite3pp::database::connect(char const*) (sqlite3pp.cpp:89)
==11682==    by 0x1021C6E3: sqlite3pp::database::database(char const*) (sqlite3pp.cpp:74)
Run Code Online (Sandbox Code Playgroud)

所以我有一个线程使用sqlitecpp调用2个不同类的2个类似函数

功能看起来像这样

void user_control::start_work_with_db( std::string db_name )
{
    if (!is_db_set) // TODO: find out how to detach from one db and connect to another.
    {
        boost::shared_ptr<sqlite3pp::database> db_( new sqlite3pp::database(db_name.c_str())); //I could not get `db = new sqlite3pp::database(DB_name.c_str());` to compile
        db = db_;
        *lu << "Connected to "<< db_name << " database and created a table with SQLite return code: " << db->execute(command_create_users_table.c_str()) << log_util::endl;
    }
}
Run Code Online (Sandbox Code Playgroud)

void users_files_service::create_files_table( std::string db_name )
{
    if(!is_db_set) // TODO: find out how to detach from one db and connect to another.
    {
        boost::shared_ptr<sqlite3pp::database> db_( new sqlite3pp::database(db_name.c_str())); //I could not get `db = new sqlite3pp::database(DB_name.c_str());` to compile
        db = db_;
        *lu << "Connected to "<< db_name << " database and created a table with SQLite return code: " << db->execute(command_create_files_table.c_str()) << log_util::endl;
        is_db_set = true;
    }
}
Run Code Online (Sandbox Code Playgroud)

和command_create_files_table看起来像

command_create_files_table = "CREATE TABLE IF NOT EXISTS files (encoded_url varchar(300) UNIQUE NOT NULL primary key, file_name varchar(150) NOT NULL, user_name varchar(65) NOT NULL, is_public BOOLEAN NOT NULL, modified DATETIME NOT NULL default CURRENT_TIMESTAMP )";
Run Code Online (Sandbox Code Playgroud)

command_create_users_table = "CREATE TABLE IF NOT EXISTS users (email varchar(100) UNIQUE NOT NULL primary key, pass varchar(100))";
Run Code Online (Sandbox Code Playgroud)

并且db是每个类的私人成员.

我想知道 - 我在代码中某处出现错误,或者SQLite不支持在一个线程上运行2个DB文件?

thk*_*ala 5

基本的SQLite库肯定支持从同一个线程打开多个DB文件 - 我已经在Linux和Windows上反复这样做了.它既可行又有用,只要你不打开自己两次打开相同的 DB文件并尝试交错事务,在这种情况下你的线程可能只是死锁 - 而不是崩溃.

此行表示堆栈损坏:

==11682==    at 0x0: ???
Run Code Online (Sandbox Code Playgroud)

您可能希望使用Valgrind进一步跟踪此问题.在我过去的答案中有一些使用Valgrind的提示.