我有一个具有以下结构的类:
class Nginx_sender
{
private:
std::vector<std::string> mMessagesBuffer;
boost::mutex mMutex;
void SendMessage(const std::string &msg)
{
mMutex.lock();
mMessagesBuffer.push_back(msg);
mMutex.unlock();
std::cout << "Vector size: " << mMessagesBuffer.size() << std::endl;
}
void NewThreadFunction()
{
while(true) {
mMutex.lock();
if (mMessagesBuffer.size() >= 1) std::cout << ">=1\n";
mMutex.unlock();
boost::this_thread::sleep(boost::posix_time::milliseconds(200));
}
}
};
int main()
{
Nginx_sender *NginxSenderHandle;
boost::thread sender(boost::bind(&Nginx_sender::NewThreadFunction, &NginxSenderHandle));
// ...
}
NewThreadFunction
在新线程中运行并检查mMessagesBuffer
. 现在我在main
函数中的任何地方调用:NginxSenderHandle->SendMessage("Test");
这会出现:Vector size: 1
第一次,2
第二次等。
但!它总是== NewThreadFunction
0。为什么会这样?