如何在 jthread 中传递带有参数和 stop_condition 的函数?

How to pass a function with arguments and stop_condition in jthread?

我正在尝试做这样的事情

#include <iostream>
#include <thread>
#include <chrono>

void doWork(char a, std::stop_token st = {}) {
    while (!st.stop_requested()) {
        std::cout << a << '\n';
    }
}

int main() {
    std::jthread t1{doWork, 'A'}, // error
                 t2{doWork, 'B'}; // error
    std::this_thread::sleep_for(std::chrono::milliseconds(50));
}

但它不会在 -std=c++2a:

的 gcc trunk 上编译
/opt/compiler-explorer/gcc-trunk-20200219/include/c++/10.0.1/thread:537:20: error: static assertion failed: std::thread arguments must be invocable after conversion to rvalues

  537 |      static_assert(is_invocable_v<decay_t<_Callable>,

      |                    ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

  538 |       decay_t<_Args>...>,

      |       ~~~~~~~~~~~~~~~~~~

甚至可以做这样的事情吗?

我认为这应该是可能的,因为我已经看到一个类似的 lambda 示例 (here):

//...
std::jthread t([&ready, &readyMutex, &readyCV] (std::stop_token st) {
    while (!stoken.stop_requested()) {
        //...
    }
});

您的实现几乎是正确的。 constraint on the invokable 是它接受 std::stop_token 作为 first 参数。所以在doWork的声明中调换顺序就可以解决了。

void doWork(std::stop_token st, char a) {
    while (!st.stop_requested()) {
        std::cout << a << '\n';
    }
}

令牌来自库实现,所以它的构造无论如何都不会让你担心。