Boost logo

Boost Users :

Subject: Re: [Boost-users] [ASIO] Access violation on io_service::work destructor
From: Daniele Barzotti (daniele.barzotti_at_[hidden])
Date: 2010-09-23 09:28:28


Il 23/09/2010 14:37, Rutger ter Borg wrote:
>>
>> Why ' thread_started = !thread_started; ' is a bad stuff?
>>
>
> (not knowing where the work object is deallocated)

In my intention the work object should be deallocated automatically when
the referent count of the shared_ptr is 0.

> the worker thread could have finished before this
> statement is executed. The thing I referred to as being 'bad stuff' was
> the allocation of a work object which is not being deallocated when the
> thread didn't start properly.
>
> [snip]
>> pMyObject->_io_work_ptr.reset(p_work);
> [/snip]
>
> I guess all your pMyObjects have shared pointers with a reference count
> of 1; you reset them all with a plain pointer (p_work).

Ops..you're right!!

I change my code with the following and now all seems to work as expected!

typedef boost::shared_ptr<boost::asio::io_service::work> io_work_ptr;

static io_work_ptr pWork;

EXTERN_C DLL_EXPORT MyObjectHandle CALL GetMyObj()
{
  if (!thread_started) {
    try {
      // create the work object on the heap
      p_work.reset( new boost::asio::io_service::work(io_service) );

      // run the IO service as a separate thread:
      io_service_thread.reset(new boost::thread(io_worker_thread));

      thread_started = !thread_started;

    } catch (boost::thread_resource_error e) {
      // Failed to create the new thread
      return 0;
    }
  }
  // create the new object
  MyObject* pMyObject = new MyObject(io_service);

  // Assign a reference to io_service work object:
  // This reference is used to counting the objects created.
  // When the last MyObject is deleted the main work object
  // is destroyed and the io_service thread ends.
  pMyObject->_io_work_ptr = p_work;

  // return the object
  return pMyObject;
};


Boost-users list run by williamkempf at hotmail.com, kalb at libertysoft.com, bjorn.karlsson at readsoft.com, gregod at cs.rpi.edu, wekempf at cox.net