将参数传递给std :: thread wrapper

时间:2017-01-20 07:08:38

标签: c++ c++14

我想实现一个小线程包装器,它在线程仍处于活动状态时提供信息,或者线程是否已完成其工作。为此,我需要将函数及其参数传递给线程类到另一个函数。我有一个简单的实现应该可以工作,但不能让它编译,我无法弄清楚如何使其工作。

这是我的代码:

#include <unistd.h>
#include <iomanip>
#include <iostream>
#include <thread>
#include <utility>

class ManagedThread
{
public:
   template< class Function, class... Args> explicit ManagedThread( Function&& f, Args&&... args);
   bool isActive() const { return mActive; }
private:
   volatile bool  mActive;
   std::thread    mThread;
};

template< class Function, class... Args>
   void threadFunction( volatile bool& active_flag, Function&& f, Args&&... args)
{
   active_flag = true;
   f( args...);
   active_flag = false;
}

template< class Function, class... Args>
   ManagedThread::ManagedThread( Function&& f, Args&&... args):
      mActive( false),
      mThread( threadFunction< Function, Args...>, std::ref( mActive), f, args...)
{
}

static void func() { std::cout << "thread 1" << std::endl; }

int main() {
   ManagedThread  mt1( func);
   std::cout << "thread 1 active = " << std::boolalpha << mt1.isActive() << std::endl;
   ::sleep( 1);
   std::cout << "thread 1 active = " << std::boolalpha << mt1.isActive() << std::endl;

   return 0;
}

我得到的编译器错误:

In file included from /usr/include/c++/5/thread:39:0,
                 from prog.cpp:4:
/usr/include/c++/5/functional: In instantiation of 'struct std::_Bind_simple<void (*(std::reference_wrapper<volatile bool>, void (*)()))(volatile bool&, void (&)())>':
/usr/include/c++/5/thread:137:59:   required from 'std::thread::thread(_Callable&&, _Args&& ...) [with _Callable = void (&)(volatile bool&, void (&)()); _Args = {std::reference_wrapper<volatile bool>, void (&)()}]'
prog.cpp:28:82:   required from 'ManagedThread::ManagedThread(Function&&, Args&& ...) [with Function = void (&)(); Args = {}]'
prog.cpp:35:28:   required from here
/usr/include/c++/5/functional:1505:61: error: no type named 'type' in 'class std::result_of<void (*(std::reference_wrapper<volatile bool>, void (*)()))(volatile bool&, void (&)())>'
       typedef typename result_of<_Callable(_Args...)>::type result_type;
                                                             ^
/usr/include/c++/5/functional:1526:9: error: no type named 'type' in 'class std::result_of<void (*(std::reference_wrapper<volatile bool>, void (*)()))(volatile bool&, void (&)())>'
         _M_invoke(_Index_tuple<_Indices...>)
         ^

此处提供了实例:https://ideone.com/jhBF1q

4 个答案:

答案 0 :(得分:7)

在错误消息中,您可以看到差异void (*)()void (&)()。这是因为std::thread's constructor参数是std::decay ed

还将std::ref添加到f

template< class Function, class... Args>
   ManagedThread::ManagedThread( Function&& f, Args&&... args):
      mActive( false),
      mThread( threadFunction< Function, Args...>, std::ref(mActive), std::ref(f), std::forward<Args>(args)...)
{
}

答案 1 :(得分:6)

@O'Neil的答案是正确的,但我想提供一种简单的lambda方法,因为你已将其标记为C++14

template<class Function, class... Args>
ManagedThread::ManagedThread(Function&& f, Args&&... args):
      mActive(false),
      mThread([&] /*()*/ { // uncomment if C++11 compatibility needed
        mActive = true;
        std::forward<Function>(f)(std::forward<Args>(args)...);
        mActive = false;
      })
{}

这将不再需要外部功能。

答案 2 :(得分:4)

O'Neil和DeiDei先来到这里,就我所知,他们是正确的。但是,我仍在发布我的问题解决方案。

以下是更好的方法:

#include <atomic>
#include <thread>
#include <utility>

class ManagedThread {

public: /* Methods: */

    template <class F, class ... Args>
    explicit ManagedThread(F && f, Args && ... args)
        : m_thread(
            [func=std::forward<F>(f), flag=&m_active](Args && ... args)
                    noexcept(noexcept(f(std::forward<Args>(args)...)))
            {
                func(std::forward<Args>(args)...);
                flag->store(false, std::memory_order_release);
            },
            std::forward<Args>(args)...)
    {}

    bool isActive() const noexcept
    { return m_active.load(std::memory_order_acquire); }

private: /* Fields: */

    std::atomic<bool> m_active{true};
    std::thread m_thread;

};

它改为使用lambdas,并正确使用std::atomic<bool>代替volatile来同步状态,还包括相应的noexcept()说明符。

另请注意,基础std::thread在销毁之前未正确连接或分离,因此导致std::terminate()被调用。

我也重写了测试代码:

#include <chrono>
#include <iostream>

int main() {
    ManagedThread mt1(
        []() noexcept
        { std::this_thread::sleep_for(std::chrono::milliseconds(500)); });
    std::cout << "thread 1 active = " << std::boolalpha << mt1.isActive()
              << std::endl;
    std::this_thread::sleep_for(std::chrono::seconds(1));
    std::cout << "thread 1 active = " << std::boolalpha << mt1.isActive()
              << std::endl;
}

答案 3 :(得分:0)

以下内容简单,优雅,据我所知,在所有当前答案中最正确(请参见下文):

template < class Function, class... Args >
ManagedThread::ManagedThread( Function&& fn, Args&&... args ) :
    mActive(false),
    mThread(
        [this]( auto&& fn2, auto&&... args2 ) -> void {
            mActive = true;
            fn2(std::forward<Args>(args2)...);
            mActive = false;
        },
        std::forward<Function>(fn), std::forward<Args>(args)...
    )
{}

DeiDei的

The answer有一个微妙但重要的缺陷:lambda通过引用获取堆栈变量,因此,如果线程在构造函数返回后启动并尝试使用堆栈变量,则可以获取堆栈-使用后释放错误。确实,使用-fsanitize=address进行编译通常足以证明问题所在。

奥尼尔的

The answer在例如任何参数都是左值,并且有点笨拙。

jotik的

The answer很接近,但是在参数既不是左值也不是成员函数时都不起作用。

相关问题