我想實現一個小線程包裝程序,該線程包裝程序在線程仍處於活動狀態或線程已完成工作時提供信息。爲此,我需要將函數及其參數傳遞給線程類執行到另一個函數。我有一個簡單的實現應該工作,但不能讓它編譯,我不知道怎麼做才能使它工作。將參數傳遞給std :: thread wrapper
這裏是我的代碼:
#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
我沒有與轉發爭論太多的經驗,但我只是某種方式得到的感覺你缺少一個['的std :: forward'(HTTP ://en.cppreference.com/w/cpp/utility/forward)call or two ...你可能想閱讀[「何時使用std :: forward轉發參數?」](http:// stackoverflow。 COM /問題/ 7257144 /時使用的-stdforward到正向參數)。 –
另請注意,您可能無法獲得您期待的結果。第一次調用'mt1.isActive()之前,您創建的線程可能會啓動,運行並結束。考慮在線程函數中添加一個短暫的睡眠,然後在'main'函數中休眠一段時間。 –
我也這麼認爲,但是我添加的每個std :: forward調用實際上使其變得更糟,即導致更多的編譯器錯誤。也許如果當前的問題解決了,我將需要(並且能夠)在我的函數中應用std :: forward調用,但首先我需要讓線程構造函數調用才能工作。 – Rene