pthread没有静态的类
pthread without static decelaration with class
在类中,我声明了线程函数。我使用了静态关键字,因为没有静态关键字,它不适用于类。
但是如果函数的类型是静态的,我无法访问该类的成员函数和公共变量
#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);
}
相关文章:
- 如果C++类在类方法中具有动态分配,但没有构造函数/析构函数或任何非静态成员,那么它仍然是POD类型吗
- #为""定义宏;静态";针对不同的上下文
- cmake如何在fedora工作站中找到boost静态库包
- 静态数据成员的问题-修复链接错误会导致编译器错误
- 将公共但非静态的成员函数与ALGLIB集成
- cmake在我的项目中所需的所有静态库都不成功
- C++从另一个类访问公共静态向量的正确方法是什么
- 基于boost的程序的静态链接——zlib问题
- 在静态库中嵌入类方法
- GCC:--静态链接到pthread的整个存档配方在最近的GCC版本中停止工作
- pthread没有静态的类
- 创建非静态成员函数的 pthread
- C++ PTHREAD 错误:非静态成员函数的使用无效
- 静态和动态pthread互斥初始化
- 当g++静态链接pthread时,导致Segmentation错误,原因何在
- C++,pthread和静态回调。 "this" 返回一个指针,指向派生的基类(第 2 部分)
- 在静态初始化期间,pthread线程变量何时开始存在
- Linux pthread——有没有办法不把所有成员都创建为静态的?
- 从静态构造函数代码调用pthread库时失败
- 你如何为 x64 编译静态 pthread-win32 库