Итак, поскольку при создании pthread объект класса 'this' передается в
нить
pthread_create
является функцией C
и ожидает, что сигнатура функции будет void* (*)(void*)
, но теперь она имеет сигнатуру void (Camera::*)(void*)
, поэтому есть две ошибки: функция должна возвращать void*
, и это тоже не статический член класса. Чтобы исправить это, сделайте функцию, возвращающую void*
, и сделайте ее static
:
void Camera::init()
{
this->quit = false;
// now that the function has the correct signature, you don't need
// to cast it (into something that it wasn't)
pthread_create(&acq, NULL, &Camera::acquireImages, this);
}
void Camera::stopAcquire()
{
this->quit = true;
}
/*static*/ void* Camera::acquiredImages(void* ptr) // make it static in the declaration
{
Camera& obj = *static_cast<Camera*>(ptr);
while(obj.quit == false){
//do something
}
return nullptr;
}
Если вы используете C ++ 11 (или новее), вам следует взглянуть на стандарт <thread>
, который значительно облегчает жизнь.
#include <thread>
struct Camera {
void init() {
quit = false;
th = std::thread(&Camera::acquireImages, this);
}
~Camera() {
stopAcquire();
}
void acquireImages() {
// no need for casting. "this" points at the object which started the thread
while(quit == false) {
std::cout << ".";
}
}
void stopAcquire() {
if(th.joinable()) {
quit = true;
th.join(); // hang here until the thread is done
}
}
std::thread th{};
bool quit = false;
};