I'am using Boost and Visual Studio 2013 which don't supports the C++ 11 memory model.
Are there any memory guarantees when starting a Boost thread? I look for a guarantee like in the Java Language Specification 17.4.5:
A call to start() on a thread happens-before any actions in the started thread.
In my case I want to create a (not thread safe) TCP client and than start a receiver thread:
struct Connection {
boost::shared_ptr<TcpClient> client;
};
auto client = boost::shared_ptr<TcpClient>{new TcpClient};
client->setTimeouts(60 * 1000, 60 * 1000);
client->connect(host, port);
auto connection = boost::shared_ptr<Connection>{new Connection};
connection->client = client;
auto receiverThread = boost::shared_ptr<thread>{new thread([&connection]() {
// can I access the client safely?
while (connection->client->isConnected()) {
// do receiving stuff
}
})};
Are the changes to client
, i. e. timeouts, host and port, visible in the started thread?
Yes. The thread didn't exist before-hand so it cannot have "stale" values (e.g. in registers). All writes prior to CreateThread are visible to the new thread.
The underlying OS functions act as implied memory barriers (CreateThread
e.g.).
See also, e.g.: C++ - Should data passed to a thread be volatile?
Side note: Consider capturing the connection
shared pointer by value. That's the whole point of shared pointers, to share ownership.