Guest User

Untitled

a guest
Jul 17th, 2018
77
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.26 KB | None | 0 0
  1. class classe {
  2. public:
  3. std::thread *THREAD = NULL;
  4. void Func() {}
  5. classe() {
  6. THREAD = new std::thread(Func);
  7. }
  8. ~classe() {
  9. delete THREAD;
  10. }
  11. };
  12.  
  13. delete[] THREAD;
  14.  
  15. #include <thread>
  16. #include <memory>
  17. #include <atomic>
  18.  
  19. class classe
  20. {
  21. public:
  22. classe() : m_thread(nullptr){}
  23.  
  24. void start()
  25. {
  26. m_running.store(true);
  27. m_thread.reset(new std::thread(&classe::worker, this));
  28. }
  29.  
  30. // thread que invoca stop() será bloqueada até que worker tenha completado
  31. void stop()
  32. {
  33. m_running.store(false);
  34. m_thread->join(); //não esqueça dessa parte =) (se seu worker estiver em foreground)
  35. }
  36. private:
  37.  
  38. void worker()
  39. {
  40. while(m_running.load())
  41. {
  42. // realize algum processo
  43. }
  44. }
  45.  
  46. std::unique_ptr<std::thread> m_thread;
  47. std::atomic<bool> m_running;
  48. };
  49.  
  50. using SPtr = std::shared_ptr<int>;
  51.  
  52. {
  53.  
  54. SPtr original(new int(10));
  55.  
  56. original.use_count(); // retorna 1
  57.  
  58. {
  59.  
  60. SPtr segundo = original;
  61.  
  62. original.use_count(); // retorna 2
  63.  
  64. // "original" e "segundo" compartilham o mesmo ponteiro para um inteiro;
  65.  
  66. } // fim do escopo, "segundo" será destruído na stack
  67.  
  68. original.use_count(); // retorna 1
  69.  
  70. } // fim do escopo, original será destruido e ficando com use_count() igual a 0 e com isso o pointero será deletado automaticamente;
Add Comment
Please, Sign In to add comment