Advertisement
GAMELASTER

std::shared_ptr test

Apr 17th, 2022
990
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.53 KB | None | 0 0
  1. #include <iostream>
  2. #include <memory>
  3. #include <vector>
  4. #include <thread>
  5. #include <chrono>
  6.  
  7. class Packet
  8. {
  9. public:
  10.   Packet()
  11.   {
  12.     std::cout << "Packet construction" << std::endl;
  13.   }
  14.  
  15.   virtual ~Packet()
  16.   {
  17.     std::cout << "Packet destruction" << std::endl;
  18.   }
  19.  
  20.   std::vector<uint8_t> data;
  21. };
  22.  
  23. void thread1Func(std::shared_ptr<Packet> pkt)
  24. {
  25.   std::cout << "Thread 1 processing packet, ptr: " << std::hex << reinterpret_cast<void*>(&pkt->data[0]) << std::endl;
  26.   std::this_thread::sleep_for(std::chrono::milliseconds(1000));
  27.   std::cout << "Thread 1 finished!" << std::endl;
  28. }
  29.  
  30. void thread2Func(std::shared_ptr<Packet> pkt)
  31. {
  32.   std::this_thread::sleep_for(std::chrono::milliseconds(1000));
  33.   std::cout << "Thread 2 processing packet, ptr: " << std::hex << reinterpret_cast<void*>(&pkt->data[0]) << std::endl;
  34.   std::this_thread::sleep_for(std::chrono::milliseconds(1000));
  35.   std::cout << "Thread 2 finished!" << std::endl;
  36. }
  37.  
  38. int main()
  39. {
  40.   std::thread thread1;
  41.   std::thread thread2;
  42.   {
  43.     auto pkt = std::make_shared<Packet>();
  44.     pkt->data = std::vector<uint8_t>(6);
  45.     for (uint8_t i = 0; i < 6; i++)
  46.       pkt->data[i] = i + 1;
  47.     thread1 = std::thread(thread1Func, pkt);
  48.     thread2 = std::thread(thread2Func, pkt);
  49.   }
  50.   thread1.detach();
  51.   thread2.detach();
  52.  
  53.   std::this_thread::sleep_for(std::chrono::milliseconds(4000));
  54.  
  55.   std::cout << "4 seconds elapsed, exiting..." << std::endl;
  56.  
  57.   if (thread1.joinable()) thread1.join();
  58.   if (thread1.joinable()) thread2.join();
  59.  
  60.   return 0;
  61. }
  62.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement