thread_work_pool.cpp 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. #include "thread_work_pool.h"
  2. #include "core/os/os.h"
  3. void ThreadWorkPool::_thread_function(ThreadData *p_thread) {
  4. while (true) {
  5. p_thread->start.wait();
  6. if (p_thread->exit.load()) {
  7. break;
  8. }
  9. p_thread->work->work();
  10. p_thread->completed.post();
  11. }
  12. }
  13. void ThreadWorkPool::init(int p_thread_count) {
  14. ERR_FAIL_COND(threads != nullptr);
  15. if (p_thread_count < 0) {
  16. p_thread_count = OS::get_singleton()->get_processor_count();
  17. }
  18. thread_count = p_thread_count;
  19. threads = memnew_arr(ThreadData, thread_count);
  20. for (uint32_t i = 0; i < thread_count; i++) {
  21. threads[i].exit.store(false);
  22. threads[i].thread = memnew(std::thread(ThreadWorkPool::_thread_function, &threads[i]));
  23. }
  24. }
  25. void ThreadWorkPool::finish() {
  26. if (threads == nullptr) {
  27. return;
  28. }
  29. for (uint32_t i = 0; i < thread_count; i++) {
  30. threads[i].exit.store(true);
  31. threads[i].start.post();
  32. }
  33. for (uint32_t i = 0; i < thread_count; i++) {
  34. threads[i].thread->join();
  35. memdelete(threads[i].thread);
  36. }
  37. memdelete_arr(threads);
  38. threads = nullptr;
  39. }
  40. ThreadWorkPool::~ThreadWorkPool() {
  41. finish();
  42. }