aj3423
aj3423

Reputation: 2611

Why is it ok for boost this_thread::interrupt to work without a try-catch?

I tested with this code. Two threads, thread_1 prints a string every 200 milliseconds, thread_2 terminates thread_1 in 3 seconds.

int main() {
    boost::thread t1([&]() {
        while(1) {
            boost::this_thread::interruption_point();
            cout << "t1 running" << endl;
            Sleep(200);
        }
        cout << "it never goes here" << endl;
    });
    boost::thread t2([&]() {
        Sleep(3000); // wait 3 seconds to terminate thread 1
        cout << "interrupt t1" << endl;
        t1.interrupt(); // thread 1 should raise a thread_interrupted exception ?
    });

    t1.join();
    t2.join();
    Sleep(5000); // sleep 5 seconds waiting for the crash
}

I expect the code to crash but it doesn't. Then I guess there's a try-catch from boost::thread, I search the keyword catch in all of "thread.hpp" and "thread_data.hpp" but found nothing.

How does it work? Thanks.

Upvotes: 1

Views: 275

Answers (1)

sehe
sehe

Reputation: 393829

The library implementation (the source files, not the headers) contain proxy functions that handle the error.

As you can see in the phtreads variant, it also does some other housekeeping: http://www.boost.org/doc/libs/1_56_0/libs/thread/src/pthread/thread.cpp

    namespace
    {
        extern "C"
        {
            static void* thread_proxy(void* param)
            {
                boost::detail::thread_data_ptr thread_info = static_cast<boost::detail::thread_data_base*>(param)->self;
                thread_info->self.reset();
                detail::set_current_thread_data(thread_info.get());
#if defined BOOST_THREAD_PROVIDES_INTERRUPTIONS
                BOOST_TRY
                {
#endif
                    thread_info->run();
#if defined BOOST_THREAD_PROVIDES_INTERRUPTIONS

                }
                BOOST_CATCH (thread_interrupted const&)
                {
                }
// Removed as it stops the debugger identifying the cause of the exception
// Unhandled exceptions still cause the application to terminate
//                 BOOST_CATCH(...)
//                 {
//                   throw;
//
//                     std::terminate();
//                 }
                BOOST_CATCH_END
#endif
                detail::tls_destructor(thread_info.get());
                detail::set_current_thread_data(0);
                boost::lock_guard<boost::mutex> lock(thread_info->data_mutex);
                thread_info->done=true;
                thread_info->done_condition.notify_all();

                return 0;
            }
        }
    }

Upvotes: 4

Related Questions