2

I am using std::thread to create a thread, but looks like there is no API can tell if this operation success or failure. Is there any way to know this information?

Tinggo
  • 1,127
  • 1
  • 9
  • 18

3 Answers3

1

See reference for std::thread constructor:

std::system_error if the thread could not be started.

This is the general practice in C++. When constructor fails, you raise an exception, otherwise your object is in an awkward invalid state, which is something standard library usually avoids.

Aykhan Hagverdili
  • 28,141
  • 6
  • 41
  • 93
1

The constructor of std::thread throws an exception in the case of a failure.

https://en.cppreference.com/w/cpp/thread/thread/thread

Exceptions 3)
std::system_error if the thread could not be started. The exception may represent the error condition std::errc::resource_unavailable_try_again or another implementation-specific error condition.

If you use OS-specific threading mechanics, you may look up their respective (C) APIs:
Windows
Linux

Raildex
  • 3,406
  • 1
  • 18
  • 42
1

There are two popular approaches to determining success of unreliable operations in modern programming languages.

  • Have a returned status code or readable error code, which indicates whether the operation was successful. This is the older approach, used in C programs and hence the POSIX interfaces many of them use. With this style, functions and methods have the semantics of only trying to perform an operation. On return from the function or method you know that an attempt has been made, but you do not know whether it was successful.

  • Throw an exception if, and only if, the operation failed. This is the newer approach, used in well written C++ programs and the C++ standard library. With this style, functions, methods and constructors have the semantics of doing an operation. On return from the function, method or constructor you know that the operation has been successfull.

So, in your particular case, return from the thread constructor means the thread was successfully created, and there is no need to check a status code.

Raedwald
  • 46,613
  • 43
  • 151
  • 237