【问题标题】:mem_fun fails, pthread and class ptrmem_fun 失败,pthread 和类 ptr
【发布时间】:2009-01-19 05:14:40
【问题描述】:

pthreadvoid *(*start_routine)(void* userPtr) 作为其参数,我希望我可以使用std::mem_fun 来解决我的问题,但我不能。

我想使用函数void * threadFunc() 并让userPtr 充当(userPtr->threadFunc()) 类。有没有类似std::mem_func的功能可以使用?

【问题讨论】:

    标签: c++ pthreads std member-functions


    【解决方案1】:

    一种方法是使用调用主线程函数的全局函数:

    class MyThreadClass {
    public:
      void main(); // Your real thread function
    };
    
    void thread_starter(void *arg) {
      reinterpret_cast<MyThreadClass*>(arg)->main();
    }
    

    然后,当你想启动线程时:

    MyThreadClass *th = new MyThreadClass();
    pthread_create(..., ..., &thread_starter, (void*)th);
    

    另一方面,如果您真的不需要手动使用 pthreads,那么看看 Boost.Thread 可能是个好主意,这是一个很好的 C++ 线程库。在那里,您可以获得线程、锁、互斥锁等类,并且可以以更加面向对象的方式进行多线程处理。

    【讨论】:

    • thread_started 也可以是 MyThreadClass 中的静态函数。
    • 我会把 extern "C" 放在函数之前,因为 pthread 是一个 C 函数,它使用 C 调用约定来调用你的东西。不知道 POSIX 对 pthread 说了什么。也许它需要它能够调用 C++ 函数,但我非常怀疑它。
    • 我做了这样的事情,一个静态函数,它调用带有 S 前缀的实际函数
    猜你喜欢
    • 1970-01-01
    • 2017-05-16
    • 2017-11-21
    • 2014-12-17
    • 2023-03-30
    • 2017-03-01
    • 2011-02-24
    • 1970-01-01
    • 2021-04-06
    相关资源
    最近更新 更多