Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <memory>
- #include <vector>
- #include <thread>
- #include <chrono>
- class Packet
- {
- public:
- Packet()
- {
- std::cout << "Packet construction" << std::endl;
- }
- virtual ~Packet()
- {
- std::cout << "Packet destruction" << std::endl;
- }
- std::vector<uint8_t> data;
- };
- void thread1Func(std::shared_ptr<Packet> pkt)
- {
- std::cout << "Thread 1 processing packet, ptr: " << std::hex << reinterpret_cast<void*>(&pkt->data[0]) << std::endl;
- std::this_thread::sleep_for(std::chrono::milliseconds(1000));
- std::cout << "Thread 1 finished!" << std::endl;
- }
- void thread2Func(std::shared_ptr<Packet> pkt)
- {
- std::this_thread::sleep_for(std::chrono::milliseconds(1000));
- std::cout << "Thread 2 processing packet, ptr: " << std::hex << reinterpret_cast<void*>(&pkt->data[0]) << std::endl;
- std::this_thread::sleep_for(std::chrono::milliseconds(1000));
- std::cout << "Thread 2 finished!" << std::endl;
- }
- int main()
- {
- std::thread thread1;
- std::thread thread2;
- {
- auto pkt = std::make_shared<Packet>();
- pkt->data = std::vector<uint8_t>(6);
- for (uint8_t i = 0; i < 6; i++)
- pkt->data[i] = i + 1;
- thread1 = std::thread(thread1Func, pkt);
- thread2 = std::thread(thread2Func, pkt);
- }
- thread1.detach();
- thread2.detach();
- std::this_thread::sleep_for(std::chrono::milliseconds(4000));
- std::cout << "4 seconds elapsed, exiting..." << std::endl;
- if (thread1.joinable()) thread1.join();
- if (thread1.joinable()) thread2.join();
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement