uiii
uiii

Reputation: 519

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.

Upvotes: 3

Views: 1713

Answers (2)

Gaetano Mendola
Gaetano Mendola

Reputation: 1394

boost::thread is not thread safe.

Upvotes: 0

Tudor
Tudor

Reputation: 62439

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.

Upvotes: 2

Related Questions