thread.cpp 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. /*
  2. * Copyright (c) 2006-2021, RT-Thread Development Team
  3. *
  4. * SPDX-License-Identifier: Apache-2.0
  5. *
  6. * Change Logs:
  7. * Date Author Notes
  8. * 2021-04-27 flybreak the first version.
  9. */
  10. #include "thread"
  11. #include "__utils.h"
  12. #define _RT_NPROCS 0
  13. namespace std
  14. {
  15. extern "C"
  16. {
  17. static void* execute_native_thread_routine(void *p)
  18. {
  19. thread::invoker_base* t = static_cast<thread::invoker_base*>(p);
  20. thread::invoker_base_ptr local;
  21. local.swap(t->this_ptr); // tranfer the ownership of the invoker into the thread entry
  22. local->invoke();
  23. return NULL;
  24. }
  25. }
  26. void thread::start_thread(invoker_base_ptr b)
  27. {
  28. auto raw_ptr = b.get();
  29. // transfer the ownership of the invoker to the new thread
  30. raw_ptr->this_ptr = std::move(b);
  31. int err = pthread_create(&_m_thr.__cpp_thread_t, NULL,
  32. &execute_native_thread_routine, raw_ptr);
  33. if (err)
  34. {
  35. raw_ptr->this_ptr.reset();
  36. throw_system_error(err, "Failed to create a thread");
  37. }
  38. }
  39. thread::~thread()
  40. {
  41. if (joinable()) // when either not joined or not detached
  42. terminate();
  43. }
  44. void thread::join()
  45. {
  46. int err = EINVAL;
  47. if (joinable())
  48. err = pthread_join(native_handle(), NULL);
  49. if (err)
  50. {
  51. throw_system_error(err, "thread::join failed");
  52. }
  53. _m_thr = id();
  54. }
  55. void thread::detach()
  56. {
  57. int err = EINVAL;
  58. if (joinable())
  59. err = pthread_detach(native_handle());
  60. if (err)
  61. {
  62. throw_system_error(err, "thread::detach failed");
  63. }
  64. _m_thr = id();
  65. }
  66. // TODO: not yet actually implemented.
  67. // The standard states that the returned value should only be considered a hint.
  68. unsigned thread::hardware_concurrency() noexcept
  69. {
  70. int __n = _RT_NPROCS;
  71. if (__n < 0)
  72. __n = 0;
  73. return __n;
  74. }
  75. }