不能在pthread_create函数中转换* void(MyClass :: *)(void *)到void *(*)(void *) [英] cannot convert '*void(MyClass::*)(void*) to void*(*)(void*) in pthread_create function

查看:760
本文介绍了不能在pthread_create函数中转换* void(MyClass :: *)(void *)到void *(*)(void *)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图创建一个类CameraManager的新线程,但我有以下错误:

i'm trying to create a new thread with a class "CameraManager" but i have the following error:


* pthread_create函数中的void(CameraManager :: *)(void *)to void *(*)(void *)

cannot convert '*void(CameraManager:: * )(void*) to void*( * )(void*) in pthread_create function

在cameramanager.h文件中:

i defined in the cameramanager.h file:

public:
void *dequeueLoop(void *ptr);

和cameramanager.cpp

and in the cameramanager.cpp

void CameraManager::startDequeuing(){
dequeuing = true;
dequeueThreadId = pthread_create(&dequeueThread, NULL, &CameraManager::dequeueLoop, NULL);
}

void *CameraManager::dequeueLoop(void *ptr){
while(dequeuing){
    highSpeedCamera->dequeue();
    highSpeedCamera->enqueue();
}



我不想将dequeueLoop声明为静态函数,将dequeueLoop声明为类的好友函数,但是它没有类变量'highSpeedCamera'和'dequeuing'的范围,编译器也告诉我'dequeueLoop'没有在这个范围内声明

I don't want to declare dequeueLoop as a static function i also tried to declare dequeueLoop as a class friend function in the following way but then it doesn't have scope on class variables 'highSpeedCamera' and 'dequeuing' and the compiler also tell me that 'dequeueLoop' was not declared in this scope

让dequeueLoop成为朋友的功能我做了:

to make dequeueLoop a friend function i did:

cameramanager.h

cameramanager.h

public:
friend void *dequeueLoop(void *ptr);

cameramanager.cpp

cameramanager.cpp

void CameraManager::startDequeuing(){
    dequeuing = true;
    dequeueThreadId = pthread_create(&dequeueThread, NULL, &CameraManager::dequeueLoop, NULL);
}
void *dequeueLoop(void *ptr){
    while(dequeuing){
        highSpeedCamera->dequeue();
        highSpeedCamera->enqueue();
    }
}

我在做错了什么?

推荐答案


我不想声明 dequeueLoop 一个静态函数

如果你想使用pthreads,那么你需要一个静态或非成员函数作为入口点。你可以传递指向你的对象的指针到这个函数,使用它作为非静态成员函数的trampoline:

If you want to use pthreads, then you'll need a static or non-member function for the entry point. You can pass a pointer to your object to this function, using it as a trampoline into the non-static member function:

static void * dequeueEntry(void * self) {
    return static_cast<CameraManager*>(self)->dequeueLoop();
}

dequeueThreadId = pthread_create(
    &dequeueThread, NULL, 
    &CameraManager::dequeueEntry, // <-- pointer to trampoline function
    this);                        // <-- pointer to object for member function

或者,如果你有一个现代编译器,你可以使用标准线程库:

Alternatively, if you have a modern compiler, you could use the standard thread library instead:

std::thread thread(&CameraManager::dequeLoop, this);

这篇关于不能在pthread_create函数中转换* void(MyClass :: *)(void *)到void *(*)(void *)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆