#include <thread>
#include <iostream>
#include <chrono>
#include <atomic>
#include <condition_variable>
#include <memory>
class TestThread {
public:
std::mutex m_mutex;
std::atomic_bool m_isPause;
std::atomic_bool m_isRunning;
std::condition_variable m_cv;
std::unique_ptr<std::thread> m_thread;
TestThread() : m_isPause(true), m_isRunning(false) {}
~TestThread() {
if (m_thread && m_thread->joinable()) {
m_thread->join();
}
}
void runProcess();
void pause();
void resume();
void start();
void stop();
};
void TestThread::runProcess() {
std:: cout << "hello " << std::endl;
int i = 0;
while (m_isRunning) {
{
std::unique_lock<std::mutex> lock(m_mutex);
m_cv.wait(lock, [this] { return !m_isPause.load(); });
}
if (!m_isRunning) break;
std::cout << "current process progress: " << i << std::endl;
std::this_thread::sleep_for(std::chrono::seconds(1));
++i;
}
}
void TestThread::pause() {
m_isPause = true;
}
void TestThread::resume() {
m_isPause = false;
m_cv.notify_one();
}
void TestThread::start() {
if (!m_thread || !m_thread->joinable()) {
m_isRunning = true;
m_isPause = false;
m_thread = std::make_unique<std::thread>(&TestThread::runProcess, this);
}
}
void TestThread::stop() {
m_isRunning = false;
m_isPause = false;
m_cv.notify_all();
if (m_thread && m_thread->joinable()) {
m_thread->join();
}
m_thread.reset();
}
int main() {
TestThread testThread;
char c;
while ((c = getchar()) != 'q') {
switch (c) {
case 'o': //启动线程
testThread.start();
break;
case 'p': //暂停
testThread.pause();
break;
case 'r': //继续执行
testThread.resume();
break;
case 's': //结束线程
testThread.stop();
break;
}
}
return 0;
}
12-05
2283
07-08
“相关推荐”对你有帮助么?
-
非常没帮助
-
没帮助
-
一般
-
有帮助
-
非常有帮助
提交