2017-08-10 78 views
1

这是对a question I got answered yesterday的跟进。指向成员对象的指针 - 中断线程

我试图让成员函数中断线程,但我不知道是什么,这些错误是:

[[email protected] projects]$ g++ -o test test.cpp -lpthread 
test.cpp: In instantiation of ‘InterruptibleThread::InterruptibleThread(Function&&, Args&& ...)::<lambda(std::atomic_bool&, std::atomic_bool&, auto:1&&, Args&& ...)> [with auto:1 = void (MyClass::*)(int); Function = void (MyClass::*)(int); Args = {MyClass*, int}; std::atomic_bool = std::atomic<bool>]’: 
/usr/local/include/c++/6.3.0/type_traits:2481:26: required by substitution of ‘template<class _Fn, class ... _Args> static std::__result_of_success<decltype (declval<_Fn>()((declval<_Args>)()...)), std::__invoke_other> std::__result_of_other_impl::_S_test(int) [with _Fn = InterruptibleThread::InterruptibleThread(Function&&, Args&& ...) [with Function = void (MyClass::*)(int); Args = {MyClass*, int}]::<lambda(std::atomic_bool&, std::atomic_bool&, auto:1&&, MyClass*&&, int&&)>; _Args = {std::reference_wrapper<std::atomic<bool> >, std::reference_wrapper<std::atomic<bool> >, void (MyClass::*)(int), MyClass*, int}]’ 
/usr/local/include/c++/6.3.0/type_traits:2492:55: required from ‘struct std::__result_of_impl<false, false, InterruptibleThread::InterruptibleThread(Function&&, Args&& ...) [with Function = void (MyClass::*)(int); Args = {MyClass*, int}]::<lambda(std::atomic_bool&, std::atomic_bool&, auto:1&&, MyClass*&&, int&&)>, std::reference_wrapper<std::atomic<bool> >, std::reference_wrapper<std::atomic<bool> >, void (MyClass::*)(int), MyClass*, int>’ 
/usr/local/include/c++/6.3.0/type_traits:2496:12: required from ‘class std::result_of<InterruptibleThread::InterruptibleThread(Function&&, Args&& ...) [with Function = void (MyClass::*)(int); Args = {MyClass*, int}]::<lambda(std::atomic_bool&, std::atomic_bool&, auto:1&&, MyClass*&&, int&&)>(std::reference_wrapper<std::atomic<bool> >, std::reference_wrapper<std::atomic<bool> >, void (MyClass::*)(int), MyClass*, int)>’ 
/usr/local/include/c++/6.3.0/functional:1365:61: required from ‘struct std::_Bind_simple<InterruptibleThread::InterruptibleThread(Function&&, Args&& ...) [with Function = void (MyClass::*)(int); Args = {MyClass*, int}]::<lambda(std::atomic_bool&, std::atomic_bool&, auto:1&&, MyClass*&&, int&&)>(std::reference_wrapper<std::atomic<bool> >, std::reference_wrapper<std::atomic<bool> >, void (MyClass::*)(int), MyClass*, int)>’ 
/usr/local/include/c++/6.3.0/thread:137:26: required from ‘std::thread::thread(_Callable&&, _Args&& ...) [with _Callable = InterruptibleThread::InterruptibleThread(Function&&, Args&& ...) [with Function = void (MyClass::*)(int); Args = {MyClass*, int}]::<lambda(std::atomic_bool&, std::atomic_bool&, auto:1&&, MyClass*&&, int&&)>; _Args = {std::reference_wrapper<std::atomic<bool> >, std::reference_wrapper<std::atomic<bool> >, void (MyClass::*)(int), MyClass*, int}]’ 
test.cpp:41:33: required from ‘InterruptibleThread::InterruptibleThread(Function&&, Args&& ...) [with Function = void (MyClass::*)(int); Args = {MyClass*, int}]’ 
test.cpp:111:53: required from here 
test.cpp:36:9: error: must use ‘.*’ or ‘->*’ to call pointer-to-member function in ‘fxn (...)’, e.g. ‘(... ->* fxn) (...)’ 
     fxn(forward<Args>(args)...); 

当前代码:

using namespace std; 

class InterruptThreadException {}; 

class InterruptibleThread { 
private: 
    static thread_local atomic_bool* stopRef; 
    static thread_local atomic_bool* pauseRef; 
    atomic_bool stopFlag{false}; 
    atomic_bool pauseFlag{false}; 
    thread thrd; 

public: 
    friend void checkForInterrupt(); 
    template < typename Function, typename... Args > 
    InterruptibleThread(Function&& _fxn, Args&&... _args) 
     : thrd(
       [](atomic_bool& sr, atomic_bool& pr, auto&& fxn, Args&&... args) { 
        stopRef = &sr; 
        pauseRef = &pr; 
        fxn(forward<Args>(args)...); 
       }, 
       ref(stopFlag), 
       ref(pauseFlag), 
       forward<Function>(_fxn), 
       forward<Args>(_args)...) { 
     thrd.detach(); 
    } 
    bool stopping() const { 
     return stopFlag.load(); 
    } 

    void stop() { 
     stopFlag.store(true); 
    } 

    void pause() { 
     pauseFlag.store(true); 
     cout << "setting pause flag: " << pauseFlag.load() << endl; 
    } 

    void start() { 
     pauseFlag.store(false); 
    } 
}; 

void checkForInterrupt() { 
    cout << "Pause flag: " << InterruptibleThread::pauseRef->load() << endl; 
    cout << "Stop flag: " << InterruptibleThread::stopRef->load() << endl; 
    while (InterruptibleThread::pauseRef->load()) { 
     cout << "Paused\n"; 
     this_thread::sleep_for(chrono::seconds(1)); 
    } 
    if (!InterruptibleThread::stopRef->load()) { 
     return; 
    } 
    throw InterruptThreadException(); 
} 

thread_local atomic_bool* InterruptibleThread::stopRef = nullptr; 
thread_local atomic_bool* InterruptibleThread::pauseRef = nullptr; 

void doWork() { 
    int i = 0; 
    try { 
     while (true) { 
      cout << "Checking for interrupt: " << i++ << endl; 
      checkForInterrupt(); 
      this_thread::sleep_for(chrono::seconds(1)); 
     } 
    } catch (InterruptThreadException) { 
     cout << "Interrupted\n\n"; 
    } 
} 

class MyClass { 
private: 
    int myInt; 
    void setInt(int i) { 
     myInt = i; 
    } 

public: 
    MyClass() : myInt(1) { 
    } 
    void myWork(int i); 
    void doWork(); 
}; 

void MyClass::myWork(int i) { 
    setInt(i); 
    cout << "myInt value: " << myInt << endl; 
} 

void MyClass::doWork() { 
    InterruptibleThread t(&MyClass::myWork, this, 666); 
} 

int main() { 
    MyClass mc; 
    mc.doWork(); 

    cout << "Press enter to exit" << endl; 
    getchar(); 
    return 0; 
} 

我试过编译器的建议,得到了之后的错误与fold表达式有关(afaik是C++ 17,我不会使用超过14的任何东西)。任何想法如何让这个工作?

我有一个没有使用lambdas的工作版本,但我真的好奇如何让这与原始代码一起工作。

+0

它在我看来像你的编译器不满意你的'类interruptiblethread'的定义中的'静态'修饰符。你能把这些拿出来吗?只是为了看看它是否有帮助? –

+0

你是指静态thread_locals?如果是这样,thread_locals无论如何都是隐式静态的,但某些编译器不会明确地静态声明编译(有人纠正我,如果我错了,但我的不会) – user1324674

回答

2

指向成员函数的指针使用与指向非成员函数或其他函数的指针不同的语法来调用。由于您的案例中的Functionvoid (MyClass::*)(int),因此您需要使用语法(object.*fxn)(arg)(objectPtr->*fxn)(arg)来调用它。

如果你有访问C++ 17层的功能,你可以使用std::invoke均匀拨打不同类型的可调用的:

InterruptibleThread(Function&& _fxn, Args&&... _args) 
    : thrd(
      [](atomic_bool& sr, atomic_bool& pr, auto&& fxn, auto&&... args) { 
       stopRef = &sr; 
       pauseRef = &pr; 
       std::invoke(std::move(fxn), std::move(args)...); 
      }, 
      //... 

注:我改变Args&&... argsauto&&... args因为Args&&...可能会导致问题。

如果您没有访问C++ 17,你可以自己实现invoke相当容易:

template <typename Callable, 
      typename... Args, 
      typename = std::enable_if_t<!std::is_member_function_pointer<Callable>::value>> 
decltype(auto) invoke(Callable&& c, Args&&... args) { 
    return std::forward<Callable>(c)(std::forward<Args>(args)...); 
} 

template <typename T, 
      typename T2, 
      typename Ret, 
      typename... FuncArgs, 
      typename... Args, 
      typename = std::enable_if_t<!std::is_pointer<T2>::value>> 
decltype(auto) invoke(Ret (T::*c)(FuncArgs...), T2&& t, Args&&... args) { 
    return (std::forward<T>(t).*c)(std::forward<Args>(args)...); 
} 

template <typename T, 
      typename T2, 
      typename Ret, 
      typename... FuncArgs, 
      typename... Args> 
decltype(auto) invoke(Ret (T::*c)(FuncArgs...), T2* t, Args&&... args) { 
    return (t->*c)(std::forward<Args>(args)...); 
} 

这并不尽一切std::invoke做,但它的一切,你需要它。

+0

首先非常感谢你,这解决了一般问题。我想在这里稍微扩展一点,因为我正在使用线程的未来/承诺,并且最初在创建线程时调用了move(promise)。这个使用您的调用建议的新版本会导致在错误的时间调用该移动,如果将承诺作为参数传递,最终会破坏程序。你会碰巧知道这个的原因吗?如何在lambda中调用移动并不关心这个问题? – user1324674

+0

@ user1324674被编辑为分离成员函数参数类型和提供的参数类型。当它们不完全相同时(即,如果一个函数采用'const T',但你提供了'T &&'),让它们相同会导致推导出正确类型的问题。这可能会解决你的问题;如果没有,你需要发布你的实际代码导致你的问题。 –

+0

这里是我用来测试的代码(类似于我的实际应用程序):https://gist.github.com/anonymous/7287c1a542963ccee32b147bb850b856第140行我打电话给InterruptibleThread并通过它承诺。通常在这里调用线程时,我会调用移动。我修改了调用,但是它没有解决问题(错误看起来相同) – user1324674