Fix edge case where the thread sometimes doesn't exit gracefully
This commit is contained in:
6
.gitignore
vendored
Normal file
6
.gitignore
vendored
Normal file
@@ -0,0 +1,6 @@
|
|||||||
|
/.idea
|
||||||
|
/.cache
|
||||||
|
/.ccls-cache
|
||||||
|
/compile_commands.json
|
||||||
|
/cmake-build-debug
|
||||||
|
/build
|
@@ -14,11 +14,11 @@ namespace MultiThreading {
|
|||||||
class MultiThreading::Thread {
|
class MultiThreading::Thread {
|
||||||
private:
|
private:
|
||||||
std::thread worker;
|
std::thread worker;
|
||||||
std::function<void()> current_task;
|
std::function<void()> current_task = nullptr;
|
||||||
std::atomic<bool> busy{ false };
|
std::atomic<bool> busy = false;
|
||||||
std::mutex mtx;
|
std::mutex mtx;
|
||||||
std::condition_variable cv;
|
std::condition_variable cv;
|
||||||
bool stop = false;
|
std::atomic<bool> stop = false;
|
||||||
private:
|
private:
|
||||||
void Runner();
|
void Runner();
|
||||||
public:
|
public:
|
||||||
|
2
main.cpp
2
main.cpp
@@ -6,7 +6,7 @@
|
|||||||
|
|
||||||
using namespace MultiThreading;
|
using namespace MultiThreading;
|
||||||
void some_test_func(int32_t hello) {
|
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;
|
std::cout << "test" << std::endl;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@@ -1 +0,0 @@
|
|||||||
#include <MultiThreading/Task.h>
|
|
@@ -12,11 +12,9 @@ Thread::~Thread() {
|
|||||||
current_task = nullptr;
|
current_task = nullptr;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (Busy())
|
|
||||||
Join();
|
|
||||||
|
|
||||||
cv.notify_all();
|
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) {
|
bool Thread::SetTask(std::shared_ptr<TaskBase> task) {
|
||||||
|
Reference in New Issue
Block a user