gpt4 book ai didi

c++ - 为什么我不能通过传入的类对象参数杀死 pthread

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:54:41 25 4
gpt4 key购买 nike

我启动了一个后台线程来运行我的类函数,该任务作为无限循环执行,直到客户端决定停止。因此,当创建 pthread 时,类对象“this”被传递到线程中,我试图将其转换为类对象但得到一个空对象,谁能向我解释为什么这是行不通的?

   void Camera::init()
{
typedef void *(*ThreadFuncPtr)(void *);
this->quit=false;
pthread_create(&acq, NULL, (ThreadFuncPtr)(&Camera::_acquireImages), this);
}

void Camera::stopAcquire()
{
this->quit=true;
}

void Camera::_acquireImages(void* ptr)
{
auto obj = (Camera*) ptr; //obj after cast shows as NULL object
while(!obj->quit){
//do something
}
pthread_exit(NULL);
}

最佳答案

So since when create pthread the class object 'this' is passed into thread

pthread_createC函数并期望函数签名为 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;
};

关于c++ - 为什么我不能通过传入的类对象参数杀死 pthread,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56534083/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com