Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is boost::thread thread-safe?

is boost::thread object thread-safe? Should I lock calling of member methods of boost::thread (e.g. join) to be thread-safe?

EDIT 1: Please don't bother with my purpose. Can you simply answer the question?

EDIT 2 (for those who are not satisfied with EDIT 1): My purpose is: Consider one procedure as program for the thread, one procedure which stops that thread. Thread procedure is a while loop checking condition whether to continue. Stop procedure sets the condition to FALSE and wait to the end of the thread (join) and then perform some other actions. The point is that the stop procedure can call more than one thread.

But my question is general, consider some next billion threads calling simultaneously member methods of one thread object such as get_id(), native_handle() etc.

like image 706
uiii Avatar asked Jan 01 '26 00:01

uiii


1 Answers

Joining a thread should only be done from a single other thread (preferably the thread that started it). There is no point for thread-safety in this case

Ok, I've actually looked through the source code of boost::thread:

void thread::join()
{
    detail::thread_data_ptr const local_thread_info=(get_thread_info)();
    if(local_thread_info)
    {
        bool do_join=false;

        {
            unique_lock<mutex> lock(local_thread_info->data_mutex);
            while(!local_thread_info->done)
            {
                local_thread_info->done_condition.wait(lock);
            }
            do_join=!local_thread_info->join_started;

            if(do_join)
            {
                local_thread_info->join_started=true;
            }
            else
            {
                while(!local_thread_info->joined)
                {
                    local_thread_info->done_condition.wait(lock);
                }
            }
        }
        if(do_join)
        {
            void* result=0;
            BOOST_VERIFY(!pthread_join(local_thread_info->thread_handle,&result));
            lock_guard<mutex> lock(local_thread_info->data_mutex);
            local_thread_info->joined=true;
            local_thread_info->done_condition.notify_all();
        }

        if(thread_info==local_thread_info)
        {
            thread_info.reset();
        }
    }
}

And it appears that yes, it is thread-safe.

like image 150
Tudor Avatar answered Jan 02 '26 14:01

Tudor



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!