Reference:
https://mongodb.github.io/mongo-cxx-driver/mongocxx-v3/thread-safety/

Using the same MongoDB C++ Client in multiple threads will make application crash. This code will crash:

//all necessary includes
#include 

using namespace std;
using namespace mongocxx;

//mongodb client
client Client;

void thread_func() {
  //it crashes here!
  Client["somedb"]["somecollection"].find(...); 
}

int main() {
  uri Uri("mongodb://localhost:27017");
  Client = client(Uri);

  //just a simple couple of threads will make client fail
  for (int Index=0; Index<2; Index++) {
    thread Thread(thread_func);
    Thread.detach();
  }
}

Solution:

Make different clients for different threads.

Advertisements