【发布时间】:2014-06-06 23:05:09
【问题描述】:
所以我有一个应用程序,它是一个打开多个线程的服务器,这些线程将用于数据库查询。在我的接收函数中,我测试了我构建的查询的输出,当我计算出 ostringstream 时它看起来很好,所以我将它添加到向量中。然后我 cout 向量,它看起来也很好。这一切都是在互斥锁内完成的,所以我解锁了互斥锁。我的数据库线程处于一个 while 循环中,它检查我的 vector.size() 是否 > 0。
我遇到的问题是我的循环永远不会运行,因为它永远不会看到向量 > 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();
【问题讨论】:
-
使用线程安全队列的常规方法是使用条件变量。请参见以下示例:justsoftwaresolutions.co.uk/threading/…
-
如果你真的想要一个队列,为什么不使用
std::queue? -
谢谢,我不知道队列,但不幸的是,这个问题与向量与队列无关,我的问题仍然存在。
标签: c++ multithreading vector standard-library