std::线程实例计数不等于实际应用程序线程计数

std::thread instances count isn't equal to actual application threads count

本文关键字:线程 应用程序 不等于 std 实例      更新时间:2023-10-16

我已经创建了大约20个std::线程,但是我的系统监视器(Mac OS X Maveriscks及其调试器LLDB)只显示给我5个线程。怎么了?为什么如果我尝试创建20个线程,我反而得到5个线程?

try
{
    std::promise<bool> prm[ 20 ] = {};
    std::thread thr[ 20 ] = {};
    for (int i = 0; i < 20; ++i)
    {
        thr[ i ] = std::thread(
            [&prm, i]() 
            {
                try
                {
                    while ( ! findPasswd() );
                    prm[ i ].set_value( true );
                }
                catch(...)
                {
                    prm[ i ].set_exception( std::current_exception() );
                }
            }
        );
        thr[ i ].detach();
    }
    for (auto & pr : prm)
    {
        pr.get_future().get();
    }
}

这次与detach我有足够的线程,但之前我尝试join代替detach,只有五个线程。

解决方案不是在线程创建后立即加入线程,而是在线程创建循环结束后加入。