我有一个从套接字读取并生成数据的线程.每次操作后,线程都会检查一个std::atomic_bool标志,看它是否必须提前退出.
为了取消操作,我将取消标志设置为true,然后调用join()工作线程对象.
线程代码和取消函数看起来像这样:
std::thread work_thread;
std::atomic_bool cancel_requested{false};
void thread_func()
{
while(! cancel_requested.load(std::memory_order_relaxed))
process_next_element();
}
void cancel()
{
cancel_requested.store(true, std::memory_order_relaxed);
work_thread.join();
}
Run Code Online (Sandbox Code Playgroud)
是std::memory_order_relaxed此,将原子变量的正确的内存顺序?
我已经构建了Boost 1.68(使用来自https://gist.github.com/sim642/29caef3cc8afaa273ce6的说明,并添加link=static,shared到b2命令行中还可以构建共享库。)
库似乎正确构建,并且我已经正确设置了BOOST_INCLUDEDIR和BOOST_LIBRARYDIR环境变量。
但是,当我将以下内容添加到时CMakeLists.txt:
find_package(Boost REQUIRED COMPONENTS system context coroutine thread random REQUIRED)
Run Code Online (Sandbox Code Playgroud)
并生成MinGW Makefiles,出现以下错误:
CMake Error at C:/Users/pbelanger/AppData/Local/JetBrains/Toolbox/apps/CLion/ch-0/182.4129.15/bin/cmake/win/share/cmake-3.12/Modules/FindBoost.cmake:2044 (message):
Unable to find the requested Boost libraries.
Boost version: 1.68.0
Boost include path: C:/boost/install/include/boost-1_68
Could not find the following static Boost libraries:
boost_system
boost_context
boost_coroutine
boost_thread
boost_random
Some (but not all) of the required Boost libraries were found. You may
need to install these additional Boost libraries. Alternatively, …Run Code Online (Sandbox Code Playgroud) 我目前正在为项目使用boost :: asio,并且必须将缓冲区发送到远程端点.我当前发送数据的算法如下所示:
void send_the_data(DataElement const& data)
{
auto databuf = make_shared<std::vector<uint8_t>>(data.to_bytes());
// lambda object holds a reference to the data to prevent early destruction.
asio::async_write(this->sock,
asio::buffer(databuf),
transfer_all(),
[this, databuf](size_t bt, boost::system::error_code const& ec)
{
if(ec) this->handle_error(ec);
else this->do_the_next_thing();
assert(bt = databuf->size());
// the destructor of this lambda should clean up the data buffer here,
// after it has been handled.
});
}
Run Code Online (Sandbox Code Playgroud)
我的逻辑是,shared_ptr的lambda捕获将阻止它在async_write完成之后被销毁,然后在处理程序执行后正确清理缓冲区.
但是,我很好奇,如果主要编译器或标准允许变量的捕获被忽略,如果在lambda的主体中没有引用它,这将导致未定义的行为(由于可能访问一个在async_write调用中悬空指针),或者如果标准保证不会省略所有值捕获.
c++ ×3
boost ×2
atomic ×1
boost-asio ×1
cancellation ×1
cmake ×1
lambda ×1
lifetime ×1
windows ×1