Boost logo

Boost :

Subject: [boost] [boost.thread] how to delete this thread from within the thread and thread hangs
From: Tan, Tom (Shanghai) (TTan_at_[hidden])
Date: 2009-08-18 22:35:00

I am using boost::thread_group to create(using
thread_group::create_thread()) and dispatch threads. In order to limit
the max thread numbers, at the end of each thread, I remove the thread
from the thread_group and delete the thread itself(so that I could
decide whether new threads need to be created). However it hangs
somewhere between the creation and deletion of the last thread (say the
999th one of 999 in total).

My questions are:
-1) is it OK to delete the thread from within itself like what I do? if
not, what the best way to achieve this
-2) why does my code hangs?

Below are the related code:
//1- code to create and dispatch thread

        //mutex for map<thread_id, thread*> operations
        boost::mutex::scoped_lock lk(m_mutex_for_ptr);

        // create a thread for this->f(duplicate_hashes)
        boost::thread* p = m_thread_group.create_thread(boost::bind(

        // save the thread_id -> thread pointer map for later lookup and
        m_thread_ptrs.insert(make_pair(p->get_id(), p));

        // log to console for debug
        cout << "thread created: "
            << p->get_id() << ", "
            << m_thread_group.size() << ", " m_thread_ptrs.size() <<

//2- code of the thread execution
    void f(list<map_iterator_type>& l)

//3- code to delete the thread itself
void remove_this_thread()

        //mutex for map<thread_id, thread*> operations
        boost::mutex::scoped_lock lk(m_mutex_for_ptr);
        boost::thread::id this_id(boost::this_thread::get_id());

        map<boost::thread::id, boost::thread*>::iterator itr;

        itr = (m_thread_ptrs.find(this_id));

        if(m_thread_ptrs.end() != itr)
            // remove it from the control of thread_group
            // delete it
            delete itr->second;

            // remove from the map

            // log to console for debug
            cout << "thread erased: "
                << this_id << ", "
                << m_thread_group.size() << ", "
                << m_thread_ptrs.size() << "\n";


Boost list run by bdawes at, gregod at, cpdaniel at, john at