に私は、この基本クラスを持っている:純粋仮想関数は、ベース/派生クラス
class Base {
public:
Base();
virtual ~Base();
protected:
virtual on_next_item(std::string& item) = 0;
private:
void read_loop();
};
と、この派生クラス:Base
クラスのコンストラクタで
class Derived : public Base {
public:
Derived();
virtual ~Derived();
protected:
void on_next_item(std::string& item) override;
};
私はどのスレッドを開始していますソケットから読み取り、派生クラスで呼び出されるon_next_item()
を呼び出します。 Base
デストラクタでは、リーダースレッドはアトミックフラグによって停止します。 しかし、read_loop
はまだon_next_item
と呼ばれ、「純粋な仮想関数が呼び出されました!」というメッセージが表示されることがあります。エラー。
サブクラス(オブジェクト)は既に破棄されているため、関数はそれ以上登録されていません。
この競合状態を解決する適切な方法はありますか?完全のために
は、ここでは、読者のループです:
while (running.load())
{
string item = read();
if (running.load())
{
on_text_item(item);
}
}
実行されているフラグはBase
クラスのデストラクタでfalseに切り替えています。
編集(完全な実行している例は、問題に実行するために複数回実行する必要があります):
#include <atomic>
#include <boost/thread/thread.hpp>
#include <boost/chrono.hpp>
#include <iostream>
class Base
{
public:
Base() : running(true)
{
readerThread = new boost::thread(&Base::read_loop, this);
}
virtual ~Base()
{
running = false;
delete readerThread;
readerThread = nullptr;
}
protected:
virtual void on_next_item(std::string &item) = 0;
private:
boost::thread *readerThread;
void read_loop()
{
std::string element = "Element";
while (running.load())
{
boost::this_thread::sleep_for(boost::chrono::milliseconds(2));
on_next_item(element);
}
}
std::atomic_bool running;
};
class Derived : public Base
{
public:
Derived() : Base()
{
}
virtual ~Derived()
{
}
protected:
virtual void on_next_item(std::string &item)
{
std::cout << "On Next Item " << item << std::endl;
}
};
void constAndDestruct()
{
Derived d;
boost::this_thread::sleep_for(boost::chrono::seconds(2));
}
int main(int argc, char **argv)
{
constAndDestruct();
boost::this_thread::sleep_for(boost::chrono::seconds(2));
}
ありがとうございました!
いつものように[MCVE]を提供してください。それ以外は純粋な推測につながるだろう。 – user0042
ロジックを 'Base'のデストラクタからメンバ関数に移動することができます。それともあなたにとってうまくいかないでしょうか? –
コンストラクタでスレッドを作成するのは良い考えではありません。また、Baseクラスのコンストラクタでは、オブジェクトは完全に形成されていません(派生はまだ存在しません)。 https://stackoverflow.com/questions/30258639/when-is-it-safe-to-call-this-in-constructor-and-destructor – mksteve