gpt4 book ai didi

c++ - 将参数传递给 std::thread 包装器

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:05:25 29 4
gpt4 key购买 nike

我想实现一个小型线程包装器,用于提供线程是否仍处于事件状态或线程是否已完成其工作的信息。为此,我需要将线程类要执行的函数及其参数传递给另一个函数。我有一个应该可以工作但无法编译的简单实现,而且我不知道该怎么做才能让它工作。

这是我的代码:

#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

最佳答案

在错误消息中,您可以看到 void (*)()void (&)() 的区别。那是因为 std::thread's constructor参数是 std::decayed

同时将 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)...)
{
}

关于c++ - 将参数传递给 std::thread 包装器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41757938/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com