简体   繁体   English

为什么std :: thread在其构造函数中等待?

[英]Why does std::thread wait in its constructor?

The current implementation of the STL in Microsoft Visual C++ 2015 seems to disallow any lock-free environment to start a thread due to a mutex wait in the constructor. 由于构造函数中的互斥锁等待,Microsoft Visual C ++ 2015中STL的当前实现似乎不允许任何无锁环境启动线程。

void _Launch(_Thrd_t *_Thr)
    {   // launch a thread
    _Thrd_startX(_Thr, _Call_func, this);
    while (!_Started)
        _Cnd_waitX(_Cond, _Mtx); // <-- Why?
    }

template<class _Target> inline
    void _Launch(_Thrd_t *_Thr, _Target&& _Tg)
    {   // launch a new thread
    _LaunchPad<_Target> _Launcher(_STD forward<_Target>(_Tg));
    _Launcher._Launch(_Thr);
    }

explicit thread(_Fn&& _Fx, _Args&&... _Ax)
    {   // construct with _Fx(_Ax...)
    _Launch(&_Thr,
        _STD make_unique<tuple<decay_t<_Fn>, decay_t<_Args>...> >(
            _STD forward<_Fn>(_Fx), _STD forward<_Args>(_Ax)...));
    }

Can anybody tell me why this wait is needed? 谁能告诉我为什么需要等待吗?

I'm asking, because I currently examine a system that sometimes needs over 500ms to construct a std::thread but never shows this delay with using CreateThread . 我问,是因为我目前正在检查一个有时需要500毫秒才能构造std::thread的系统,但从未使用CreateThread表现出这种延迟。

_LaunchPad<_Target> _Launcher(_STD forward<_Target>(_Tg));

_Launcher is on the stack and is passed to the new thread. _Launcher在堆栈上,并传递给新线程。 Why? 为什么? I don't know, but this makes it important that _Launcher not go out of scope until the new thread is done with it. 我不知道,但这使得_Launcher在使用新线程完成之前不要超出范围很重要。 The wait is likely there to guarantee this. 等待可能会保证这一点。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 为什么std :: deque在默认构造函数中为其元素分配内存? - Why does std::deque allocate memory for its elements in the default constructor? 移动构造函数对于以 std::thread 和 std::mutex 作为其字段的类是否有意义? - Does move constructor makes any sense for a class that has std::thread's and std::mutex's as its fields? 如果返回值不是左值,为什么主线程要等待 std::async() 创建的线程? - Why does the main thread wait the thread created by std::async() if the return value is not hold by lvalue? std::thread 是否对其构造函数返回时发生的事情做出任何保证? - Does std::thread make any guarantee about what's happened when its constructor returns? std::thread 如何存储通过其构造函数传递的可变参数? - How does std::thread store variadic arguments passed through its constructor? 为什么std :: random_device将其复制构造函数定义为已删除? - Why does std::random_device define its copy constructor as deleted? std 线程构造函数是否采用可变参数线程 function? - Does std thread constructor take variadic thread function? std::thread 构造函数完成实际上与执行线程的开始同步吗? - Does std::thread constructor completion actually synchronize with the beginning of the thread of execution? 如果删除其参数,则另一个线程中的std :: thread是否会崩溃? - Does std::thread in another thread crash if its parameters are deleted? 为什么std :: transform使用构造函数? - Why does std::transform utilize the constructor?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM