ostringstream to vector <string> for Multithreaded Queue </string>

时间:2014-04-22 14:04:51

标签: c++ multithreading vector standard-library

所以我有一个应用程序,它是一个打开几个线程的服务器,用于数据库查询。在我的接收函数中,我测试了我构建的查询的输出,当我输出ostringstream时它看起来很好,所以我将它添加到向量中。我然后cout矢量,它也看起来很好。这都是在互斥锁中完成的,所以我解锁了互斥锁。我的数据库线程在while循环中,它检查我的vector.size()&gt; 0

我遇到的问题是我的循环永远不会运行,因为它永远不会看到向量&gt; 0(它应该是因为我能够传播vector.begin()并且它工作正常。任何人都可以查看我的代码并告诉我是否有任何可能导致此问题的问题。

#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();

1 个答案:

答案 0 :(得分:0)

我能想到的一个可能的问题是,互斥锁是在代码中的其他位置获取的,CNetworkService::DBWork()从未获得锁定。

这可能不是导致问题的原因。但是,您可以通过将mtx变量设置为CNetworkService的私有字段来阻止它,因为它用于同步队列而您不希望在其他地方使用它。

我建议您通过在mtx.lock()while(queue.size() > 0)之间打印一些内容进行测试,以查看锁定是否被获取。

P.S。 vector::erase非常昂贵。

相关问题