gpt4 book ai didi

c++ - 线程基类 C++

转载 作者:太空宇宙 更新时间:2023-11-04 16:08:50 25 4
gpt4 key购买 nike

我想做一些线程基类。我编写了代码,我认为它应该可以工作,它编译并运行但它什么都不显示。我认为,问题出在回调中,但我可能是错的。那么,我的代码有什么问题?

class ThreadedBase
{
public:
ThreadedBase(bool start = false) : m_running(false) {
if (start)
this->start();
}
virtual ~ThreadedBase() {
m_running = false;
m_thread.join();
}

bool start(){
if (m_running) {
return false;
};
m_thread = std::thread(&ThreadedBase::run, this);
m_running = true;
return true;
};

bool stop(){
if (!m_running) {
return false;
};
m_running = false;
return true;
};

protected:
virtual void threadedBlock() = 0;

void run() {
while (m_running) {
threadedBlock();
}
}

private:
std::thread m_thread;
bool m_running;
};

class Test : public ThreadedBase
{
public:
Test(bool start = true) : ThreadedBase(start) {}

void threadedBlock() {
std::cout << "Task\n";
std::this_thread::sleep_for(std::chrono::milliseconds(500));
}
};

int main()
{
Test t(true);
t.start();

std::this_thread::sleep_for(std::chrono::seconds(100));

return 0;
}

最佳答案

你需要添加:

m_running = true;

之前:

m_thread = std::thread(&ThreadedBase::run, this);

关于c++ - 线程基类 C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31054186/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com