Skip to content

Instantly share code, notes, and snippets.

@fbraem
Created Dec 12, 2015
Embed
What would you like to do?
MongoDB Multithread Test
#include "Poco/MongoDB/MongoDB.h"
#include "Poco/MongoDB/Connection.h"
#include "Poco/MongoDB/Database.h"
#include "Poco/MongoDB/Cursor.h"
#include "Poco/MongoDB/Array.h"
#include "Poco/Mutex.h"
#include <Poco/MongoDB/PoolableConnectionFactory.h>
#include <iostream>
Poco::PoolableObjectFactory<Poco::MongoDB::Connection, Poco::MongoDB::Connection::Ptr> factory("localhost:27017");
Poco::ObjectPool<Poco::MongoDB::Connection, Poco::MongoDB::Connection::Ptr> pool(factory, 16, 256);
class MongoDBRunnable : public Poco::Runnable
{
public:
MongoDBRunnable(int id) : _id(id) {}
virtual ~MongoDBRunnable() {}
virtual void run()
{
Poco::MongoDB::PooledConnection pooledConnection(pool);
Poco::MongoDB::Connection::Ptr connection = (Poco::MongoDB::Connection::Ptr) pooledConnection;
Poco::MongoDB::Database db("mongodbmt");
Poco::SharedPtr<Poco::MongoDB::InsertRequest> insert = db.createInsertRequest("documents");
insert->addNewDocument().add("id", _id);
std::cout << "_id: " << _id << ": Inserting " << std::endl;
connection->sendRequest(*insert);
Poco::SharedPtr<Poco::MongoDB::QueryRequest> query = db.createQueryRequest("documents");
query->selector().add("id", _id);
query->setNumberToReturn(1);
Poco::MongoDB::ResponseMessage response;
std::cout << "_id: " << _id << ": Querying" << std::endl;
connection->sendRequest(*query, response);
std::cout << "_id: " << _id << ": " << response.documents()[0]->toString(2) << std::endl;
int id = response.documents()[0]->get<int>("id");
if ( id != _id )
{
std::cout << "Wrong id received! " << id << std::endl;
}
Poco::SharedPtr<Poco::MongoDB::DeleteRequest> del = db.createDeleteRequest("documents");
del->selector().add("id", id);
std::cout << "_id: " << _id << ": Deleting " << std::endl;
connection->sendRequest(*del);
}
private:
int _id;
};
int main(int argc, char **argv)
{
std::vector<Poco::SharedPtr<MongoDBRunnable> > runnables;
for(int i = 0; i < 15; ++i)
{
std::cout << "Create " << i << std::endl;
runnables.push_back(new MongoDBRunnable(i));
}
for(int i = 0; i < 15; ++i)
{
Poco::SharedPtr<MongoDBRunnable> runnable = runnables.at(i);
std::cout << "Starting " << i << std::endl;
Poco::ThreadPool::defaultPool().start(*runnable);
}
Poco::ThreadPool::defaultPool().joinAll();
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment