簡體   English   中英

C ++:使用pthread_create創建新線程以運行類成員函數

[英]C++: Creating new thread using pthread_create, to run a class member function

我有以下課程:

class A
{
    private:
        int starter()
        {
             //TO_DO: pthread_create()
        }

        void* threadStartRoutine( void *pThis );
}

我想從starter()內部創建一個線程來運行threadStartRoutine()。 關於第三個參數,我遇到了編譯時錯誤,該錯誤應采用啟動例程的地址。

調用pthread_create()創建開始執行threadStartRoutine()的新線程的正確方法是什么?

我在網上看到過很多文章,說大多數編譯器不允許使用pthread_create()調用非靜態成員函數。 這是真的? 這背后的原因是什么?

我正在使用G ++在Linux-x64上編譯程序。

threadStartRountine()聲明為static

static void* threadStartRoutine( void *pThis );

否則, threadStartRoutine()的類型為:

void* (A::*)(void*)

這不是pthread_create()所需的函數指針的類型。

您有使用pthreads的理由嗎? c ++ 11在這里,為什么不使用它:

#include <iostream>
#include <thread>

void doWork()
{
   while(true) 
   {
      // Do some work;
      sleep(1); // Rest
      std::cout << "hi from worker." << std::endl;
   }
}

int main(int, char**)
{

  std::thread worker(&doWork);
  std::cout << "hello from main thread, the worker thread is busy." << std::endl;
  worker.join();

  return 0;
}

只需將普通函數用作包裝器即可。 正如hjmd所說,靜態函數可能是最好的普通函數。

如果您堅持使用本機pthreads接口,則必須提供一個普通函數作為入口點。 一個典型的例子:

class A
{
private:
    int starter()
    {
        pthread_t thr;
        int res = pthread_create(&thr, NULL, a_starter, this);
        // ...
    }
public:
    void run();
};

extern "C" void * a_starter(void * p)
{
    A * a = reinterpret_cast<A*>(p);
    a->run();
    return NULL;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM