Search code examples
c++multithreadingc++20comma-operator

Executing several actions in parallel with std::jthread and comma operator in C++20


In C++20 we got a new thread-class std::jthread that unlike old std::thread waits for thread termination in the destructor. So it becomes easy to execute several actions in parallel using unnamed jthread-objects and comma operator:

#include <thread>
#include <iostream>

int main() {
    std::jthread{ []{ std::cout << "Hello from new thread\n"; } },
        std::cout << "Hello from main thread\n";
}

This works fine, demo: https://gcc.godbolt.org/z/YPW8bq7jK

Unfortunately, Visual Studio 2019 issues a warning here:

warning C4834: discarding return value of function with 'nodiscard' attribute

because std::jthread constructor is declared as [[nodiscard]] in it. As far as I see the standard does not require this attribute: https://timsong-cpp.github.io/cppwp/n4861/thread.jthread.class.

Is it just a bug in MSVC STL, or there is really some risk associated with such jthread-usage?


Solution

  • there is really some risk associated with such jthread-usage?

    Define "such usage" and "some risk".

    The nodiscard attribute is entirely appropriate for jthread's constructors. Yes, you can write code where creating and discarding a jthread object is a meaningful, functional thing. But even if it is meaningful and functional, you still shouldn't do it. It's being cute in your code in a way that adds absolutely nothing of value. It looks like a bug, and its best not to write code that looks almost identical to broken code.

    Try to write clear, clean code that doesn't require someone to know the intimate details of the C++ comma operator and its relationship to subexpressions in order to accurately gauge its operation.

    And yes, standard library implementations are allowed to give warnings for any reason. So long as well-formed programs successfully compile and execute as described by the standard, the implementation is valid.