Monday, February 7, 2022

C++: Starting and stopping a thread

//Demonstrates how a thread can be started and stopped
#include <iostream>
#include <thread>
#include <chrono>
bool isRunning = false;
class MyClass {
public:
~MyClass() {
if (worker != nullptr) {
isRunning = false;
worker->join();
delete worker;
std::cout << "worker deleted" << std::endl;
}
}
static void Run(double duration_s) {
while (isRunning) {
std::cout << "isRunning" << std::endl;
auto startTime = std::chrono::steady_clock::now();
auto endTime = startTime + std::chrono::duration<double>(duration_s);
std::this_thread::sleep_until(endTime);
}
std::cout << "thread ended" << std::endl;
}
void Start(double duration_s) {
isRunning = true;
worker = new std::thread(Run, duration_s);
}
void Stop() {
isRunning = false;
}
private:
std::thread* worker;
};
int main() {
MyClass m;
m.Start(1);
auto startTime = std::chrono::steady_clock::now();
auto endTime = startTime + std::chrono::duration<double>(3);
std::this_thread::sleep_until(endTime);
m.Stop();
std::cout << "Main ended. Press enter...\n";
std::cin.get();
}

No comments:

Post a Comment