[英]MongoDB C++: Is mongocxx::pool thread safe?
获取连接时是否必须手动锁定mongocxx :: pool?
即这样安全吗? (从Mongo网站复制的例子)
mongocxx::instance instance{};
mongocxx::pool pool {mongocxx::uri{}};
using mongocxx::pool::entry = std::unique_ptr<client, std::function<void (client*)>>
auto threadfunc = [](mongocxx::client &client, stdx::string_view dbname) {
client[dbname]["col"].insert({});
}
// don't even bother sharing clients. Just give each thread its own,
std::thread([]() {
// pool.acquire() returns a mongo::pool::entry type
mongocxx::client *c= pool.acquire().get();
threadfunc(*c, "db1");
threadfunc(*c, "db2");
});
std::thread([]() {
mongocxx::client *c = pool.acquire().get();;
threadfunc(*c, "db2");
threadfunc(*c, "db1");
});
是的, mongocxx::pool
是线程安全的。 您可以从多个线程同时访问它。 但是,从池返回的各个mongocxx::client
对象不是线程安全的,也不是从client
获取collection
或database
等从属对象 - 您不能在线程之间共享它们。
另请注意,您的示例(不是从网站逐字复制而是从其中一个示例中修改)包含严重的编程错误。
这一行:
mongocxx::client *c= pool.acquire().get();
将获取一个池条目,然后从中提取一个裸指针。 但是,池条目将在语句结束时被销毁,从而导致底层client
对象返回到池中,从而允许另一个线程在您继续使用它时可能将其拾取。
你应该把它写成:
mongocxx::instance instance{};
mongocxx::pool pool {mongocxx::uri{}};
auto threadfunc = [](mongocxx::client &client, stdx::string_view dbname) {
client[dbname]["col"].insert({});
}
// don't even bother sharing clients. Just give each thread its own,
std::thread([]() {
// pool.acquire() returns a mongo::pool::entry type
auto c = pool.acquire();
threadfunc(*c, "db1");
threadfunc(*c, "db2");
});
std::thread([]() {
auto c = pool.acquire();
threadfunc(*c, "db2");
threadfunc(*c, "db1");
});
这样,每个线程都会保留池条目,直到它完成使用它为止,此时当c
的unique_ptr
被销毁时它将自动返回。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.