From 987ec27d9ba6aad4031e175851041482605801ba Mon Sep 17 00:00:00 2001 From: Redacted Date: Tue, 8 Apr 2025 20:32:26 -0400 Subject: [PATCH] Fix edge case where the thread sometimes doesn't exit gracefully --- .gitignore | 6 ++++++ include/MultiThreading/Thread.h | 6 +++--- main.cpp | 2 +- src/Task.cpp | 1 - src/Thread.cpp | 6 ++---- 5 files changed, 12 insertions(+), 9 deletions(-) create mode 100644 .gitignore delete mode 100644 src/Task.cpp diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..52c505d --- /dev/null +++ b/.gitignore @@ -0,0 +1,6 @@ +/.idea +/.cache +/.ccls-cache +/compile_commands.json +/cmake-build-debug +/build diff --git a/include/MultiThreading/Thread.h b/include/MultiThreading/Thread.h index 5b6e1c9..d2a1a9b 100644 --- a/include/MultiThreading/Thread.h +++ b/include/MultiThreading/Thread.h @@ -14,11 +14,11 @@ namespace MultiThreading { class MultiThreading::Thread { private: std::thread worker; - std::function current_task; - std::atomic busy{ false }; + std::function current_task = nullptr; + std::atomic busy = false; std::mutex mtx; std::condition_variable cv; - bool stop = false; + std::atomic stop = false; private: void Runner(); public: diff --git a/main.cpp b/main.cpp index 455f687..13081e6 100644 --- a/main.cpp +++ b/main.cpp @@ -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; } diff --git a/src/Task.cpp b/src/Task.cpp deleted file mode 100644 index d687331..0000000 --- a/src/Task.cpp +++ /dev/null @@ -1 +0,0 @@ -#include \ No newline at end of file diff --git a/src/Thread.cpp b/src/Thread.cpp index a9afdca..b7ae5ee 100644 --- a/src/Thread.cpp +++ b/src/Thread.cpp @@ -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 task) {