So I have an application which is a server that opens several threads which will be used for database queries. In my receive function, I tested the output for my query which I built and it looks fine when I cout the ostringstream, so I add it to a vector. I then cout the vector and it also looks fine. This is all done within a mutex lock, so then I unlock the mutex. My database threads are in a while loop which checks to see if my vector.size() > 0.
The problem I am having is that my loop never runs, because it never sees the vector > 0(Which it should be because I was able to cout the vector.begin() and it worked fine. Could anyone take a look at the code I have and tell me if there are any problems that might be causing this issue.
#Header
class CNetworkService : public Service
{
public:
CNetworkService(void);
~CNetworkService(void);
std::ostringstream query;
string record;
std::vector<string> queue;
string IP;
unsigned int Port;
void DBWork();
bool SaveLog(string insert);
protected:
virtual void handle(LogicalConnection* pClient, IncomingPacket* pRequest);
};
#Source File
//In my receive handler
mtx.lock();
query << var1 << var2;
queue.push_back(query.str());
mtx.unlock();
query.clear();
//This is the function that the database threads are looping in
void CNetworkService::DBWork()
{
while(true)
{
mtx.lock();
while(queue.size() > 0)
{
printf("Adding new record \n");
SaveLog(queue.front());
queue.erase(queue.begin());
}
mtx.unlock();
}
}
//The code in the main thread which launches each thread. StartDBThread does some reporting stuff and then lauches the DBWork function, and I can see that DBWork is getting called. In the original attempt I was trying to launch 4 threads, but for now I have scaled it back to 1 thread in order to test and get a working solution.
std::thread threads[1];
// spawn 1 threads:
for (int i=0; i<1; ++i)
threads[i] = std::thread(StartDBThread, i+1);
for (auto& th : threads) th.join();