Confused about multi-threading

93 views
Skip to first unread message

Patrick Rutkowski

unread,
Dec 21, 2017, 6:28:21 PM12/21/17
to mongodb-user
I’m writing a multi-threaded application in Python using PyMongo (so that's interpreter threads, not OS threads). The docs for PyMongo recommend using a single MongoClient() object for the whole process, which all threads share. Presumably MongoClient() is written to be safe with interpreter threads. But how about other objects? Can I share database and collection instances across threads? Or should each thread fetch its own copy of database and collection objects from the process-global MongoClient?

-Patrick

A. Jesse Jiryu Davis

unread,
Dec 21, 2017, 6:59:32 PM12/21/17
to mongodb-user
Hi Patrick. Yes, MongoClient is thread-safe. Create one MongoClient for your whole process and share it among all your threads. Database and Collection are thread-safe, too, so you can share them among threads as well, but it doesn't matter if you create a Database and Collection per thread or not: the important thing is to make only one MongoClient.

(By the way, interpreter threads *are* OS threads in Python. They can't execute Python concurrently, due to the Global Interpreter Lock, but they are nevertheless real threads.)
Reply all
Reply to author
Forward
0 new messages