这不是网络问题。这是一个关于原子的问题,但是场景围绕着网络。
我有几个线程接收网络消息。每个参数都应增加一个TotalBytesReceive
的原子变量,直到达到TotalBytes
的值为止。我的原子行为异常,可能是由于我对某些事物的误解。
在多个线程中:
size_t BytesReceived = // number of bytes received in this thread
bool IsMessageFinished = msg->IsMsgFinished(BytesReceived);
if(IsMessageFinished)
{do something else}
共享的msg对象包含
class Msg
{
std::vector<char> MessageData; // The data received for the message
const size_t TotalBytes; // The final size of the complete message
std::atomic<size_t> TotalBytesReceived; // The bytes received so far
std::mutex m_mutex; // Just for testing
public:
Msg(size_t totalbytes) : TotalBytesReceived(0), TotalBytes(totalbytes)
{
MessageData.resize(TotalBytes);
}
bool IsMsgFinished(size_t BytesReceived)
{
// std::unique_lock<std::mutex> lock(m_mutex); // uncommenting fixed the problem
size_t newtotal = TotalBytesReceived += BytesReceived;
std::stringstream ss;
ss << BytesReceived << " received. New total " << newtotal << '\n';
std::cout << ss.str(); // For diagnostics
return newtotal == TotalBytes;
}
// Other functions for setting MessageData aren't important here
}
最大的问题是,当多个线程调用IsMsgFinished
时,我的诊断输出显示newtotal
多次具有相同的值。那不可能。 (BytesReceived
永远不会为0)这里有严重错误吗?
如果我在IsMsgFinished
函数中使用了互斥锁和unique_lock,则一切正常,但我不想使用锁。