Skip to content

Instantly share code, notes, and snippets.

@shmutalov
Last active August 29, 2015 14:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save shmutalov/3894fdd22ec62334fe17 to your computer and use it in GitHub Desktop.
Save shmutalov/3894fdd22ec62334fe17 to your computer and use it in GitHub Desktop.
MapiDemoCpp
#include <string>
#include <chrono>
#include <thread>
#include <mutex>
#include <iostream>
#include <sstream>
#include <vector>
#include <algorithm>
#include <mapilib\mapi.h>
#include <WinSock2.h>
std::mutex printMutex;
void print(std::string str)
{
printMutex.lock();
std::cout << str;
printMutex.unlock();
}
int main(int argc, char* argv[])
{
using namespace std;
stringstream ss;
WSADATA WSAData;
if (WSAStartup(MAKEWORD(2, 2), &WSAData) != 0)
{
ss.clear();
ss << "Cannot initialize Windows Sockets 2.2: ERROR " << WSAGetLastError() << endl;
print(ss.str());
return -1;
}
print("Windows Sockets 2 initialized\n");
vector<thread> tasks;
for (auto i = 0; i < 64; i++)
{
tasks.push_back(thread([](int threadNum)
{
stringstream ss;
auto conn = mapi_connect("localhost", 50000, "monetdb", "monetdb", "sql", "demo");
if (conn == nullptr || mapi_error(conn))
{
ss << threadNum << ": " << mapi_error_str(conn) << endl;
ss << "WinSock error: " << WSAGetLastError() << endl;
print(ss.str());
return;
}
stringstream qss;
qss << "SELECT " << threadNum << ", NOW();";
string query = qss.str();
auto comm = mapi_query(conn, query.c_str());
if (comm == nullptr || mapi_error(conn))
{
mapi_reconnect(conn);
if (mapi_error(conn))
{
ss.clear();
ss << threadNum << ": Reconnect error: " << mapi_error_str(conn) << endl;
print(ss.str());
return;
}
comm = mapi_query(conn, query.c_str());
if (comm == nullptr || mapi_error(conn))
{
mapi_disconnect(conn);
mapi_destroy(conn);
return;
}
}
while (mapi_fetch_row(comm) > 0)
{
ss.clear();
ss << threadNum << ": " << "[" << mapi_fetch_field(comm, 0) << ", " << mapi_fetch_field(comm, 1) << "]" << endl;
print(ss.str());
}
if (mapi_error(conn))
{
ss.clear();
ss << threadNum << ": " << mapi_error_str(conn) << endl;
print(ss.str());
}
mapi_close_handle(comm);
mapi_disconnect(conn);
mapi_destroy(conn);
return;
}, i)
);
}
this_thread::sleep_for(chrono::milliseconds(1000));
for (auto iter = tasks.begin(); iter != tasks.end(); iter++)
{
try
{
iter->join();
}
catch (exception& e)
{
ss.clear();
ss << "Exception: " << e.what() << endl;
print(ss.str());
}
}
print("Finished");
getchar();
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment