gpt4 book ai didi

c++ - SQLite——C++多线程读写

转载 作者:行者123 更新时间:2023-11-30 01:39:37 24 4
gpt4 key购买 nike

我有 C++11 应用程序,它使用多线程。每个线程都可以读取或写入数据库,例如。做 INSERT, UPDATE, DELETE, SELECT .我为 SQLite 启用了序列化模式,因此可以在线程之间共享连接。

但是,我不知道如何运行查询。我可以只运行单个查询并通过 sqlite3_prepare_v2 创建语句吗? ?或者,我应该通过 std::lock_guard<std::mutex> 添加自己的锁吗?并做类似的事情:

Thread #1
db.lock()
db.query("....").execute()
db.unlock()

Thread #2
db.lock()
res = db.query("....").select()
while(res) res.row()
db.unlock()

或者还有其他方法吗?我一直在寻找一些示例代码,但一无所获。

最佳答案

Serialized模式你不需要手动锁定来执行查询。根据 SQLite 文档:

In this mode (which is the default when SQLite is compiled with SQLITE_THREADSAFE=1) the SQLite library will itself serialize access to database connections and prepared statements so that the application is free to use the same database connection or the same prepared statement in different threads at the same time.

也可以考虑使用WAL以获得更多的并发性。在这种模式下,读写可以同时进行。在连接字符串中包含 journal mode=WAL 以启用它。

关于c++ - SQLite——C++多线程读写,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45264494/

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