threadable.h 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. #pragma once
  2. #include <util/system/thread.h>
  3. #include <util/system/defaults.h>
  4. #include <util/generic/ptr.h>
  5. //deprecated. use future.h instead
  6. template <class T>
  7. class TThreadable: public T {
  8. public:
  9. using TThreadProc = TThread::TThreadProc;
  10. inline TThreadable()
  11. : Arg(nullptr)
  12. , ThreadInit(nullptr)
  13. {
  14. }
  15. inline int Run(void* arg = nullptr, size_t stackSize = 0, TThreadProc init = DefInit) {
  16. if (Thread_) {
  17. return 1;
  18. }
  19. Arg = arg;
  20. ThreadInit = init;
  21. try {
  22. THolder<TThread> thread(new TThread(TThread::TParams(Dispatch, this, stackSize)));
  23. thread->Start();
  24. Thread_.Swap(thread);
  25. } catch (...) {
  26. return 1;
  27. }
  28. return 0;
  29. }
  30. inline int Join(void** result = nullptr) {
  31. if (!Thread_) {
  32. return 1;
  33. }
  34. try {
  35. void* ret = Thread_->Join();
  36. if (result) {
  37. *result = ret;
  38. }
  39. Thread_.Destroy();
  40. return 0;
  41. } catch (...) {
  42. }
  43. return 1;
  44. }
  45. protected:
  46. static TThreadable<T>* This(void* ptr) {
  47. return (TThreadable<T>*)ptr;
  48. }
  49. static void* Dispatch(void* ptr) {
  50. void* result = This(ptr)->ThreadInit(This(ptr)->Arg);
  51. return result ? result : (void*)(size_t)This(ptr)->T::Run(This(ptr)->Arg);
  52. }
  53. static void* DefInit(void*) {
  54. return nullptr;
  55. }
  56. public:
  57. void* Arg;
  58. TThreadProc ThreadInit;
  59. private:
  60. THolder<TThread> Thread_;
  61. };