| 1 | #include <iostream>
|
|---|
| 2 | #include <thread>
|
|---|
| 3 | #include <boost/thread.hpp>
|
|---|
| 4 |
|
|---|
| 5 | void loop() {
|
|---|
| 6 | while(true) sleep(1);
|
|---|
| 7 | }
|
|---|
| 8 | template<class T>
|
|---|
| 9 | void cancel(T & thread) {
|
|---|
| 10 | sleep(1); // just in case
|
|---|
| 11 | pthread_cancel(thread.native_handle()); // low-level interuption
|
|---|
| 12 | }
|
|---|
| 13 |
|
|---|
| 14 | template<class T>
|
|---|
| 15 | void join(T & thread) {
|
|---|
| 16 | pthread_join(thread.native_handle(), nullptr);
|
|---|
| 17 | }
|
|---|
| 18 |
|
|---|
| 19 | int main() {
|
|---|
| 20 | std::thread std_thread1(loop);
|
|---|
| 21 | cancel(std_thread1);
|
|---|
| 22 | join(std_thread1);
|
|---|
| 23 | std::cout << "std::thread pthread_joined" << std::endl;
|
|---|
| 24 |
|
|---|
| 25 | std::thread std_thread2(loop);
|
|---|
| 26 | cancel(std_thread2);
|
|---|
| 27 | std_thread1.join();
|
|---|
| 28 | std::cout << "std::thread joined" << std::endl;
|
|---|
| 29 |
|
|---|
| 30 | boost::thread boost_thread1(loop);
|
|---|
| 31 | cancel(boost_thread1);
|
|---|
| 32 | join(boost_thread1);
|
|---|
| 33 | std::cout << "boost::thread pthread_joined" << std::endl;
|
|---|
| 34 |
|
|---|
| 35 | boost::thread boost_thread2(loop);
|
|---|
| 36 | cancel(boost_thread2);
|
|---|
| 37 | std::cout << "waiting for boost::thread to join() forever... :(" << std::endl;
|
|---|
| 38 | boost_thread2.join();
|
|---|
| 39 | std::cout << "so we never reach this point" << std::endl;
|
|---|
| 40 |
|
|---|
| 41 | return 0;
|
|---|
| 42 | }
|
|---|