Boost logo

Boost :

Subject: Re: [boost] thread_safe_ptr class interest request
From: Kyku (kwrzalik_at_[hidden])
Date: 2010-07-28 12:52:46


2010/7/28 Giovanni Piero Deretta <gpderetta_at_[hidden]>:
> On Wed, Jul 28, 2010 at 2:44 PM, Philippe Vaucher
> <philippe.vaucher_at_[hidden]> wrote:
>> Hello,
>>
>> I've made a thread_safe_ptr class available at http://codepad.org/PxDEGaFm
>>
>> The idea is to use it like so:
>>
>> std::string data = "Hello world;";
>> thread_safe_ptr<std::string> data_ptr(&data);
>>
>> void thread1()
>> {
>>    data_ptr->resize(3);
>> }
>>
>> void thread2()
>> {
>>    *data_ptr = "yeah";
>> }
>>
>> boost::thread t1(&thread1);
>> boost::thread t2(&thread1);
>> t1.join(); t2.join();
>>
>>
>
> std::stack<int> deq = ...;
> thread_safe_ptr<std::stack<int> > data_ptr(&data);
>
>
> int pop() {
>      int my_top = data_ptr->top();
>      data_ptr->pop(); // will this pop my_top?
>      return my_pop;
> }
>
> Unfortunately the interface of a class must be designed to be
> threadsafe, you can't just bolt on thread safety by locking every
> member function. Such a wrapper might have some limited use, but it
> could lead to a false sense of security.
>
> Just my 0.2 €

I was about to make the same comment, however I noticed there is a
thread_safe_ptr::scoped_lock with pointer semantics for such
occasions. I think this solution is nice and would happily see it as a
part of boost smart pointer or thread libraries.

int pop() {
      thread_safe_ptr< std::stack<int> >::scoped_lock lock(data_ptr);
      int my_top = lock->top();
      lock->pop();
      return my_pop;
}

Yours,
Krzysztof Wrzalik


Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk