【发布时间】:2021-12-05 17:32:26
【问题描述】:
我正在尝试使用新的 jthread 并已启动 std::jthread,其中确实调用了 operator(),但我无法让它停止。我想通过将其作为函数对象调用来创建线程。
my_thrd = std::make_shared<std::jthread>(&Test::operator(), &test);
如果我的 Test 类的 operater() 写成如下,它会编译:
void Test::operator()()
{
using namespace std::literals;
while (!token.stop_requested()) {
std::cout << "Working ...\n" << std::flush;
std::this_thread::sleep_for(5s);
}
close_connection();
}
但由于它没有停止,我想我需要以某种方式将std::stop_token 传递给class Test,就像这样。
void Test::operator()(std::stop_token token) { ... }
但这不能编译。我也确实更改了标题。
/usr/lib/gcc/x86_64-pc-linux-gnu/10.3.0/include/g++-v10/thread: 在'static std::thread std::jthread::_S_create(std:: stop_source&, _Callable&&, _Args&& ...) [with _Callable = void (Test::)(std::stop_token); _Args = {测试}]': /usr/lib/gcc/x86_64-pc-linux-gnu/10.3.0/include/g++-v10/thread:450:28: 来自 'std::jthread::jthread(_Callable&&, _Args&& ...) [ with _Callable = void (Test::)(std::stop_token); _Args = {测试}; =无效]' /usr/lib/gcc/x86_64-pc-linux-gnu/10.3.0/include/g++-v10/bits/stl_construct.h:97:14: 来自'constexpr decltype (::new(void*(0) ) _Tp) std::construct_at(_Tp*, _Args&& ...) [with _Tp = std::jthread; _Args = {void (Test::)(std::stop_token), Test}; decltype (::new(void*(0)) _Tp) = std::jthread*]’ /usr/lib/gcc/x86_64-pc-linux-gnu/10.3.0/include/g++-v10/bits/alloc_traits.h:514:4: 来自'static constexpr void std::allocator_traitsstd::allocator<_chart>::construct(std::allocator_traitsstd::allocator<_chart>::allocator_type&, _Up*, _Args&& ...) [with _Up = std::jthread; _Args = {void (Test::)(std::stop_token), Test}; _Tp = std::jthread; std::allocator_traitsstd::allocator<_chart>::allocator_type = std::allocatorsstd::jthread]'
想法?
【问题讨论】:
标签: c++ multithreading c++20