Fix edge case where the thread sometimes doesn't exit gracefully

This commit is contained in:
2025-04-08 20:32:26 -04:00
parent 09a8bd0868
commit 987ec27d9b
5 changed files with 12 additions and 9 deletions

6
.gitignore vendored Normal file
View File

@@ -0,0 +1,6 @@
/.idea
/.cache
/.ccls-cache
/compile_commands.json
/cmake-build-debug
/build

View File

@@ -14,11 +14,11 @@ namespace MultiThreading {
class MultiThreading::Thread {
private:
std::thread worker;
std::function<void()> current_task;
std::atomic<bool> busy{ false };
std::function<void()> current_task = nullptr;
std::atomic<bool> busy = false;
std::mutex mtx;
std::condition_variable cv;
bool stop = false;
std::atomic<bool> stop = false;
private:
void Runner();
public:

View File

@@ -6,7 +6,7 @@
using namespace MultiThreading;
void some_test_func(int32_t hello) {
for (unsigned int i = 0; i < 4000000000; i++)
for (unsigned int i = 0; i < 400; i++)
std::cout << "test" << std::endl;
}

View File

@@ -1 +0,0 @@
#include <MultiThreading/Task.h>

View File

@@ -12,11 +12,9 @@ Thread::~Thread() {
current_task = nullptr;
}
if (Busy())
Join();
cv.notify_all();
// Thread exits gracefully. If it does not, your program will likely freeze forever.
Join();
// Thread exits gracefully.
}
bool Thread::SetTask(std::shared_ptr<TaskBase> task) {