I’m using the Thrift framework to handle IPC between a couple of apps.
There seems to be a slight race condition issue that I want to solve, but there is also a thread safety issue that has sprung up with this solution.
TSimpleServer (Thrift code) has code that looks like this:
void TSimpleServer::serve()
{
// ...
while(!stop_) { // ... }
}
void TSimpleServer::stop()
{
stop_ = true;
// ...
}
So if I launch a new thread that runs this function:
void workerFunction()
{
// server is of type TSimpleServer
server.serve(); // blocks here
}
And try stopping it from a different thread:
void StopServer()
{
server.stop(); // called from a separate thread
}
Isn’t it possible that the thread running serve() can read from the unprotected stop_ property of TSimpleServer while the thread from stop() is writing to it?
Is this a non-issue for some reason I’m overlooking? Any help on synchronizing this would be much appreciated.
This shouldn’t be an issue. Any write to a property-aligned variable that fits processor word (4 or 8 bytes) is atomic. In other words it’s impossible to read its value WHILE another thread is writing to it. So, the code is perfectly correct.