用C ++创建线程进程

时间:2013-02-21 13:18:12

标签: c++ pthreads

首先,线程和pthread之间有什么区别。我应该在C ++中使用什么。

我正在尝试使用pthread,如下所示:

//MyPatcher.h

class MyPatcher
{
   public:
     void createThread();

   private:
     void * Checkingdata(void *arg);
}

// MyPatcher.cpp
#include "MyPatcher.h"
#include <pthread.h>
using namespace std;

void MyPatcher::createThread()
{
  pthread_t threadDataReading;

  if(pthread_create(&threadDataReading, NULL, Checkingdata, NULL))  
    printf("Could not create thread\n");

  if(pthread_join(threadReadingGps, NULL))  
    printf("Could not join thread\n");
}

void * MyPatcher::Checkingdata(void *arg)
{
  return NULL;
}

但我遇到了这些问题:

./MyPatcher.cpp:71:73: error: argument of type 'void* (SampleApp::MyPatcher::)(void*)' does not match 'void* (*)(void*)'

我该如何解决这个问题?

//然后我也尝试使用线程:

//MyPatcher.h

    class MyPatcher
    {
       public:
         void createThread();

       private:
         void Checkingdata();
    }

    // MyPatcher.cpp
    #include "MyPatcher.h"
    #include <thread>
    using namespace std;

    void MyPatcher::createThread()
    {
      pthread_t threadDataReading(Checkingdata);

      threadDataReading.join();
    }

    void MyPatcher::Checkingdata()
    {

    }

但我遇到了这个问题:错误:没有匹配函数来调用&#39; std :: thread :: thread()&#39;

4 个答案:

答案 0 :(得分:4)

  

首先,线程和pthread之间有什么区别。

pthread是一个线程库实现,可以用C,C ++和其他语言访问。

thread是std :: thread,一个C ++对象(C ++ 11的一部分) - 至少我认为你的意思是线程。

  

我应该在C ++中使用什么。

如果您有支持它的编译器,请使用std :: thread。否则,看看你是否可以使用boost :: thread。如果这两个都不是出于任何原因的好选项(你的项目不允许使用boost,你必须使用旧的C ++编译器等),那么pthread是一个很好的选择。

  

如何解决此[特定编译]问题?

您的实现尝试将C ++对象成员函数作为自由函数指针传递(应该不起作用)。你应该创建一个自由函数,而不是调用你的对象函数。

编辑[std :: thread example]:

class MyPatcher
{
   public:
     void createThread();

   private:
     void Checkingdata();
}

// MyPatcher.cpp
#include "MyPatcher.h"
#include <thread>
#include <functional> // std::bind
using namespace std;

void MyPatcher::createThread()
{
    // std::bind -> return a functor with signature void functor(void);
    std::thread threadDataReading(std::bind(&MyPatcher::Checkingdata, this));

    threadDataReading.join();
}

void MyPatcher::Checkingdata()
{
}

答案 1 :(得分:1)

pthread_create()需要一个简单的C风格函数指针。您正在传递一个成员函数指针,如果没有(通常是隐式的)this参数,则无法调用它。

你可以通过定义一个普通函数的小包装器来使它工作:

static void * Checkingdata(void *arg)
{
  static_cast<MyPatcher*>(arg)->CheckingData();
}

然后将该函数传递给pthread_create(),并将类实例的地址作为最后一个参数传递(而您有NULL)。

答案 2 :(得分:1)

传递给pthread_create的函数不能是成员函数。您可以通过创建静态函数来解决此问题。由于您将NULL作为参数传递,因此我将重用void *arg来传递对象:

 static void * Checkingdata(void *self)
 {
      MyPatcher *me = reinterpret_cast<MyPatcher*>(self);
      me->DoCheckingData();
 }

 void * DoCheckingdata();   // Does the things you want to do. 

原因是线程函数没有“this-pointer”作为隐藏参数传递给memberfunction。

还有其他选择,例如使用std::thread,它将std::function对象作为其参数 - 或者可以转换为td::function

答案 3 :(得分:0)

如果您正在开发绿色领域项目,并且您正在使用可用c ++ 11兼容编译器的平台,我强烈建议您考虑使用std::thread。正如命名空间所暗示的那样,线程支持现在内置于标准库中。谷歌“C ++ 11线程”提供了大量的教程信息。