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?