【问题标题】:QNX Object oriented threads in c++C ++中的QNX面向对象线程
【发布时间】:2009-01-07 11:30:06
【问题描述】:

我想在 QNX 中使用 c++ 和线程创建一个并行的面向对象系统。我该怎么做?

我试过了:

pthread_t our_thread_id;
pthread_create(&our_thread_id, NULL, &functionA ,NULL);

函数 A 是指向函数的指针:

void *functionA()
{ //do something
}

但是,此函数仅适用于 C 而不是 C++。如何让它在 C++ 中工作?

【问题讨论】:

    标签: c++ multithreading qnx


    【解决方案1】:

    "How do I pass a pointer-to-member-function to a signal handler, X event callback, system call that starts a thread/task, etc?"

    简而言之,您传递一个静态函数(“蹦床”)作为函数指针。您将“this”作为用户定义的参数传递。然后静态函数将调用反弹回真实对象。

    例如:

    class Thread {
    public:
        int Create()
        {
            return pthread_create(&m_id, NULL, start_routine_trampoline, this);
        }
    
    protected:
        virtual void *start_routine() = 0;
    
    private:
        static void *start_routine_trampoline(void *p)
        {
            Thread *pThis = (Thread *)p;
            return pThis->start_routine();
        }
    };
    

    并且您需要确保 C++ 函数具有与 pthread_create 预期的相同的调用约定。

    【讨论】:

      【解决方案2】:

      您的functionA 不是指向函数的指针,而是返回void* 的函数。该函数还应采用 void* 作为参数。此参数用于传递指向线程所需数据的指针。

      如果你替换

      void* functionA() {
      

      void functionA(void* threadData) {
      

      我希望它可以在 C 和 C++ 中工作。

      【讨论】:

        【解决方案3】:

        我认为您需要将functionA 声明为extern "C"(并给它正确的签名,请参阅documentation for pthreads on QNX)。此函数将this 实例作为用户参数:

        extern "C"
        {
           void* DoSomethingInAThread(void* pGenericThis)
           {
             YourClass* pThis = reinterpret_cast<YourClass*>(pGenericThis);
             pThis->DoSomethingInAThread();
           }
        }
        
        int main()
        {
          YourClass* pSomeInstance = new YourClass();
          pthread_t our_thread_id;
          pthread_create(&our_thread_id, NULL, &DoSomethingInAThread, pSomeInstance);
        }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2011-04-16
          • 2015-02-12
          • 1970-01-01
          • 1970-01-01
          • 2012-02-24
          • 2017-03-24
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多