Thread.cpp 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. #include "core/Thread.hpp"
  2. #include "ErrorSimulator.hpp"
  3. #include "core/Logger.hpp"
  4. using Core::Mutex;
  5. using Core::MutexGuard;
  6. using Core::Thread;
  7. void Mutex::lock() noexcept {
  8. try {
  9. FAIL_STEP_THROW();
  10. mutex.lock();
  11. } catch(std::exception& e) {
  12. REPORT(LogLevel::ERROR, "Could not lock mutex: #", e.what());
  13. }
  14. }
  15. void Mutex::unlock() noexcept {
  16. try {
  17. FAIL_STEP_THROW();
  18. mutex.unlock();
  19. } catch(std::exception& e) {
  20. REPORT(LogLevel::ERROR, "Could not unlock mutex: #", e.what());
  21. }
  22. }
  23. MutexGuard::MutexGuard(Mutex& m) : mutex(m) {
  24. mutex.lock();
  25. }
  26. MutexGuard::~MutexGuard() {
  27. mutex.unlock();
  28. }
  29. Thread::Thread() : thread() {
  30. }
  31. Thread::Thread(Thread&& other) noexcept : thread() {
  32. swap(other);
  33. }
  34. Thread::~Thread() {
  35. join();
  36. }
  37. Thread& Thread::operator=(Thread&& other) noexcept {
  38. if(this != &other) {
  39. join();
  40. thread = Core::move(other.thread);
  41. }
  42. return *this;
  43. }
  44. void Core::Thread::swap(Thread& other) {
  45. Core::swap(thread, other.thread);
  46. }
  47. bool Thread::start(Function f, void* p) {
  48. if(thread.joinable()) {
  49. return true;
  50. }
  51. try {
  52. FAIL_STEP_THROW();
  53. thread = std::thread([f, p]() { f(p); });
  54. } catch(std::exception& e) {
  55. REPORT(LogLevel::ERROR, "Could not start thread: #", e.what());
  56. return true;
  57. }
  58. return false;
  59. }
  60. bool Thread::join() {
  61. if(thread.joinable()) {
  62. try {
  63. FAIL_STEP_THROW();
  64. thread.join();
  65. } catch(std::exception& e) {
  66. REPORT(LogLevel::ERROR, "Could not join thread: #", e.what());
  67. return true;
  68. }
  69. }
  70. return false;
  71. }