c++ - 没有类静态声明的 pthread

标签 c++ linux multithreading pthreads

在类中我声明了线程函数。我使用了 static 关键字,因为没有 static 关键字它不能与类一起使用。

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

#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;
}

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

最佳答案

您不需要任何静态成员函数。您可以使用 pthread_create 的 argument 参数,无状态 lambda 函数衰减为普通函数指针,使代码几乎看起来像您实际编写的代码:

Godbolt 链接: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);
}

关于c++ - 没有类静态声明的 pthread,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56376540/

相关文章:

javascript - Chrome 中的嵌套 Web Worker

java - 如何使用synchronized关键字避免过时数据?

c++ - 人类可读的 type_info.name()

c++ win32 列表框和 slider 创建 windows 应用程序

c++ - 计算着色器管道创建崩溃

linux - cURL cookie 语法(来自 bash CLI,不是 cookie 文件)

c# - .NET 4.0 和可怕的 OnUserPreferenceChanged 挂起

c++ - 使用 c-preprocessor 自动生成函数转发器

linux - -O2 优化会破坏某些机器上的 C++ 代码

linux - EXT3 文件系统预摘要 Material