[英]Creating thread process in C++
首先,线程和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()
{
}
但是我遇到了这个问题:错误:没有匹配的函数调用'std :: thread :: thread()'
首先,线程和pthread有什么区别。
pthread是一个线程库实现,可以使用C,C ++和其他语言进行访问。
线程是std :: thread,一个C ++对象(C ++ 11的一部分)-至少我认为这是线程的意思。
我应该在C ++中使用什么。
如果您有支持它的编译器,请使用std :: thread。 否则,请查看是否可以使用boost :: thread。 如果无论出于何种原因,这两个都不是很好的选择(您的项目不允许使用boost,则必须使用旧的C ++编译器,等等),那么pthread是一个不错的选择。
我该如何解决[特定的编译]问题?
您的实现尝试将C ++对象成员函数作为自由函数指针传递(这不起作用)。 您应该创建一个自由函数,而不是调用您的对象函数。
编辑[std :: thread示例]:
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()
{
}
pthread_create()
需要普通的C样式函数指针。 您正在传递给它一个成员函数指针,如果没有(通常是隐式) this
参数,则无法调用该成员函数指针。
您可以通过定义一个简单的包装器使其工作:
static void * Checkingdata(void *arg)
{
static_cast<MyPatcher*>(arg)->CheckingData();
}
然后,将该函数与类实例的地址一起作为最后一个参数传递给pthread_create()
(而您拥有NULL)。
传递给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”作为隐藏参数传递给成员函数。
还有其他选择,例如使用std::thread
,它将std::function
对象作为其参数-或可以转换为td::function
。
如果您正在开发一个绿色项目,并且正在使用一个兼容c ++ 11的编译器,那么我强烈建议考虑使用std::thread
。 如名称空间所示,线程支持现在已内置在标准库中。 Google的“ C ++ 11线程”提供了大量教程信息。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.