Question

I use the thread local storage with boost. I have a global variable :

boost::thread_specific_ptr<MyDataClass> p_timeline_ctx;

and I have the following class, which encapsulates a boost::thread object and contains an additionnal data object :

class MyThread {
   private :
      boost::thread t;
      MyDataClass d;

   public :
      MyThread():c() {}

      void start(void) {
         ptr.reset(this->d);
         this->t = boost::thread(&MyThread::worker, this);
      }

      void worker(void) {
         // do something
      }

};

I do not get any error when compiling. But on runtime, when the worker function exits and the thread ends, I get a "glibc ... free ... invalid pointer" error.

I guess this comes from the fact that, according to the boost doc, the thread_specific_ptr tries to delete the object it points to when threads end. But I do not see how to solve the problem.

Was it helpful?

Solution

The thread specific pointer takes ownership. You could reset it:

p_timeline_ctx.reset(0);

or intialize it with a deep copy in the first place:

ptr.reset(new MyDataStruct(d));

However, you'd be far better off just passing the reference as an argument to the thread pointer.

In fact, the worker is already an instance member function, so, why do you need a thread-specific copy of this:

#include <boost/bind.hpp>
#include <boost/thread.hpp>

#include <iostream>

struct MyDataClass { };

class MyThread {
    private :
        boost::thread t;
        MyDataClass d;

    public :
        MyThread(): d() {}

        void start(void) {
            t = boost::thread(&MyThread::worker, this);
        }

        void worker() {
            // just use this->d here
        }
};

int main()
{
}

Or using a static thread function:

#include <boost/bind.hpp>
#include <boost/thread.hpp>

#include <iostream>

struct MyDataClass { };

class MyThread {
    private :
        boost::thread t;
        MyDataClass d;

    public :
        MyThread(): d() {}

        void start(void) {
            t = boost::thread(&MyThread::worker, boost::ref(d));
        }

        static void worker(MyDataClass&) {
            // do something
        }
};

int main()
{
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top