线程中的成员函数指针
Member-Function Pointer in Threads
我创建了一个类,它使用成员函数数组来初始化线程数组。
我不知道如何将函数指针传递给线程构造函数。关于此主题的文档很少。
类.h
#define N_FUNCTIONS 23
class TradingData
{
public:
void EXECUTE();
void Book();
void Charts();
void Company();
void Dividends();
void Earnings();
void EffectiveSpread();
void Financials();
void KeyStats();
void LargestTrades();
void List();
void Logo();
void News();
void OHLC();
void Peers();
void Previous();
void Price();
void Quote();
void Relevant();
void Splits();
void TimeSeries();
void VolumeByVenue();
void S_Previous();
void S_Symbols();
private:
std::thread p_thread[N_FUNCTIONS];
typedef void (TradingData::*overall)();
overall p_overall[N_FUNCTIONS] = {
&TradingData::Book,
&TradingData::Charts,
&TradingData::Company,
&TradingData::Dividends,
&TradingData::Earnings,
&TradingData::EffectiveSpread,
&TradingData::Financials,
&TradingData::KeyStats,
&TradingData::LargestTrades,
&TradingData::List,
&TradingData::Logo,
&TradingData::News,
&TradingData::OHLC,
&TradingData::Peers,
&TradingData::Previous,
&TradingData::Price,
&TradingData::Quote,
&TradingData::Relevant,
&TradingData::Splits,
&TradingData::TimeSeries,
&TradingData::VolumeByVenue,
&TradingData::S_Symbols,
&TradingData::S_Previous
};
类.cpp
void TradingData::EXECUTE()
{
for (int i = 0; i < N_FUNCTIONS; i++) {
p_thread[i] = std::thread((this->*p_overall[i])()); //here is the problem
}
for (int i = 0; i < N_FUNCTIONS; i++) {
p_thread[i].join();
}
std::cout << "finished successfully" <<std::endl;
}
我收到下一个错误: 错误 C2440 ":无法从"void"转换为"std::thread">
你应该写call;
p_thread[i] = std::thread(TradingData::p_overall[i], this);
如果调用成员函数,则类名将包含在调用中。
p_thread[i] = std::thread((this->*p_overall[i])());
这会将正在调用的成员函数的返回值传递给线程构造函数。但是,由于您不返回可调用的内容,因此当然,这甚至无法编译。
请注意,调用成员函数的对象实际上是作为第一个参数传递给要调用的函数的(对您透明(。这是您在创建线程时需要反映的内容:
p_thread[i] = std::thread(p_overall[i], *this);
启动时的线程现在将使用*this
作为第一个参数调用成员函数。请注意,成员函数实际上接受引用,尽管函数内部的this
被定义为指针,从而取消引用 this 指针...
有时,lambda 可能很有用,如下所示:
std::thread t(this, i {(this->*p_overall[i](((; }(;
当然,在特定情况下矫枉过正,但在将来的某个时候在其他情况下可能会有用......
相关文章:
- QMetaObject invokeMethod的基于函数指针的语法
- C++-试图将函数指针推回到另一个CPP文件中的矢量时出错
- c++r值引用应用于函数指针
- 模板函数指针和lambda
- 是否可以将llvm::FunctionType转换为C/C++原始函数指针
- 带有类的函数指针
- () 函子后面的括号,而不是函数指针?
- 全局作用域中函数指针的赋值
- 使用"Task"函数指针队列定义作业管理器
- 将成员函数指针作为参数传递给模板方法
- 如何创建对象函数指针C++映射?
- 匹配函数指针作为模板参数?
- 通过函数指针定义类范围之外的方法
- 存储在类中的函数指针
- C++从函数指针数组调用函数
- 将返回值存储在函数指针数组的指针中是如何工作的?
- 整数键映射到头文件中的成员函数指针
- 从类成员函数到类 C 函数指针的转换
- 如何将内联匿名函数分配给C++函数指针
- 将字符缓冲区强制转换为函数指针