With this code:
void yield_sleep(void)
{
using namespace std::chrono;
static size_t thread_num;
auto start{high_resolution_clock::now()};
std::this_thread::yield();
auto end{high_resolution_clock::now()};
std::cout << thread_num++
<< "|Waiting for: "
<< duration_cast<microseconds>(end - start).count()
<< " ms."
<< std::endl;
}
int main(void)
{
std::vector<std::thread> tp(62434);
std::generate(tp.begin(), tp.end(), []() { return std::thread(yield_sleep); });
std::for_each(tp.begin(), tp.end(), [](auto& t) { t.join(); });
}
The program create ~32718 thread and throw an exception:
terminate called after throwing an instance of 'std::system_error'
what(): Resource temporarily unavailable
But in /proc/sys/kernel/threads-max
the value is 62434. What is the problem ? why my program throw an exception during create threads ?
As mentioned by @1201ProgramAlarm and @Francois Andrieux in the comments. The thread-max
value is a system wide limit and for creating much more threads we need to some modifications in kernel settings: