启动 Boost 线程时的保证

Guarantees when starting a Boost thread

我正在使用 Boost 和 Visual Studio 2013 don't supports the C++ 11 memory model

启动 Boost 线程时是否有任何内存保证?我在 Java Language Specification 17.4.5:

中寻找保证

A call to start() on a thread happens-before any actions in the started thread.

在我的例子中,我想创建一个(非线程安全的)TCP 客户端,然后启动一个接收线程:

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
  }
})};

client 的变化吗? e.超时、主机和端口,在启动的线程中可见吗?

是的。该线程不存在 before-hand,因此它不能具有 "stale" 值(例如在寄存器中)。 CreateThread 之前的所有写入对新线程都是可见的。

底层 OS 函数充当隐含的内存屏障(CreateThread 例如)。

另见,例如:C++ - Should data passed to a thread be volatile?


旁注:考虑按值捕获 connection 共享指针。这就是共享指针的全部意义,共享所有权。