Boost logo

Boost Users :

Subject: Re: [Boost-users] [ASIO] Where to use CoInitizeEx
From: Zachary Turner (divisortheory_at_[hidden])
Date: 2009-06-03 09:44:49


On Wed, Jun 3, 2009 at 8:35 AM, Ovanes Markarian <om_boost_at_[hidden]>wrote:

>
> On Wed, Jun 3, 2009 at 3:21 PM, Daniele Barzotti <
> daniele.barzotti_at_[hidden]> wrote:
>
>>
>>
>> void io_worker_thread(void)
>> {
>> #if (WIN32)
>> CoInitializeEx(NULL, COINIT_APARTMENTTHREADED);
>> #endif
>>
>> io_service.run();
>>
>> #if (WIN32)
>> CoUninitialize();
>> #endif
>> };
>>
>
> It is better to use at least RAII here. This approach is not exception safe
> and if io_service.run() throws an exception CoUnintialize() will not be
> called.
>
>

For per-thread COM Initialization in the presence of boost I almost always
do the following:

//Put in a widely visible header file somewhere
struct com_init;
extern boost::thread_specific_ptr<com_init> com_initialized;

//In a CPP file somewhere
boost::thread_specific_ptr<com_init> com_initialized;

struct com_init
{
public:
    com_init() { CoInitialize(NULL); }
    ~com_init() { CoUninitialize(); }

    static void verify_com_init()
    {
        if (!com_initialized)
            com_initialized.reset(new com_init());
    }
};

For threads you create yourself, call com_init::verify_com_init() at the
beginning of the thread function, for functions that run in threads you
don't create, call com_init::verify_com_init() at the beginning of every
invocation.



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