2017-01-04 1 views
2

接続を取得中に手動でmongocxx :: poolをロックする必要がありますか?MongoDB C++: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"); 
}); 

答えて

3

はい、mongocxx::poolはスレッドセーフです。同時に複数のスレッドからアクセスできます。しかし、個々のmongocxx::clientオブジェクトがプールから返されないスレッドセーフです、またclientから入手collectionまたはdatabaseなどの従属オブジェクトです - あなたは、スレッド間でそれらを共有してはなりません。

例(ウェブサイトからそのままコピーされていますが、例の1つから変更されています)には深刻なプログラミングエラーが含まれています。

このライン:

mongocxx::client *c= pool.acquire().get(); 

はプールエントリーを取得します、それから、裸のポインタを抽出します。ただし、プールエントリはステートメントの終わりに破棄され、基になるclientオブジェクトがプールに返され、別のスレッドが引き続きそのスレッドを使用しながら使用する可能性があります。

あなたがこれを書く必要があります。cunique_ptrが破壊されたときに自動的に戻されるその時点で、それを使用して終了するまで

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"); 
}); 

そのように、各スレッドは、プールのエントリを保持します。

+0

@xcoratあなたが質問したことに対して最高の答えをアップヴォートしたり受け入れたりするのは丁寧です。 – acm

+0

そう!私はちょうど答えを読む:p(jk、ええ、ちょうどそれを読んで、ありがとう:) – xcorat

+0

そして、ええ、私はあなたがそれを修正した方法に正確に私のコードを変更して終了し、質問を編集したと思ったが、 't。再度、感謝します! – xcorat

関連する問題