pthread没有静态的类

pthread without static decelaration with class

本文关键字:静态 pthread      更新时间:2023-10-16

在类中,我声明了线程函数。我使用了静态关键字,因为没有静态关键字,它不适用于类。

但是如果函数的类型是静态的,我无法访问该类的成员函数和公共变量

#include <iostream>
#include <pthread.h>
using namespace std;
class Base{
private:
    static  void * fpga_read(void*); // Thread function
    void foo_2();
public:
    /* member variables */
    void foo(void);
protected:
    int b;
};

void Base::foo(void)
{
    pthread_t id;
    pthread_create(&id, NULL,fpga_read,NULL);
    cout << "nInside base class" << endl;
}
void * Base::fpga_read(void *p)
{
    cout << "nInside thread function " << endl;
    // error: invalid use of member ‘Base::b’ in static member function
    cout << "Value of B inside thread class" << b;
    int b;
}
int main()
{
    Base a;
    a.foo();
    pthread_exit(NULL);
    return 0;
}

任何人都可以告诉我如何在没有静态关键字的情况下使用线程函数。 所以我可以访问所有类变量。

不需要任何静态成员函数。您可以使用 pthread_create 的参数参数,并且无状态 lambda 函数衰减到正常的函数指针来制作几乎与您实际编写的代码:

神电链接:https://godbolt.org/z/QIGNUX


#include <iostream>
#include <pthread.h>
class Base {
public:
    Base(int state) noexcept : b{state} {}
    void foo();
private:
    int b;
    void fpga_read() {
        std::cout << "Value of B inside thread class" << b;
    }
};
void Base::foo()
{
    pthread_t thread;
    pthread_create(&thread, nullptr, [](void* that) -> void* {
        Base* this_ = static_cast<Base*>(that);
        this_->fpga_read();
        return nullptr;
    }, static_cast<void*>(this));
    pthread_join(thread, nullptr);
}

pthread_create,就像所有特定于操作系统的线程创建API(Windows中的CreateThread等(一样,有一个"void*"参数传递给线程函数。

您可以使用它来传递指向类的指针

class A
{
    void ThreadToUse() {}
    static void Thread2(void* p) 
    {
        A* a = (A*)p;
        p->ThreadToUse();
    }
    void foo()
    {
        pthread_create(&A::Thread2,(void*)this);
    }
};

也就是说,您也可以以标准方式使用具有相同功能的 C++11 std::thread:

void foo()
{
    std::thread t(&A::Thread2,this);
}