线程中的成员函数指针

Member-Function Pointer in Threads

本文关键字:函数 指针 成员 线程      更新时间:2023-10-16

我创建了一个类,它使用成员函数数组来初始化线程数组。

我不知道如何将函数指针传递给线程构造函数。关于此主题的文档很少。

类.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](((; }(;

当然,在特定情况下矫枉过正,但在将来的某个时候在其他情况下可能会有用......