|
Boost Users : |
Subject: Re: [Boost-users] [Atomic] [Tread] Proposal for Synchronized<T>
From: Vicente J. Botet Escriba (vicente.botet_at_[hidden])
Date: 2013-02-19 13:23:41
Le 19/02/13 17:58, Gabriel Bizzotto a écrit :
> Hi !
>
> I've created two simples classes that helped me avoid data races when
> sharing objects among threads.
>
> The idea is to declare objects that need for synchronization as
> Synchronized<T>, which holds a T and a mutex. To use the T, a Get
> function has to be called that returns a proxy, which holds a pointer
> to the T and a scoped lock on the mutex. The proxy defines operator->
> and operator* to give access to the T. To have acces to the T, one has
> to create the proxy. As long as the proxy exists, the mutex associated
> with the T is locked, effectively preventing use by other threads.
>
> For more details and examples, I've already published the classes here
> http://codereview.stackexchange.com/questions/15632/force-locking-for-thread-safety/15742#15742
>
>
> I find the scheme general purpose enough to fit the Atomic lib, or
> perhaps Thread.
>
> Please manifest yourselves if there is any interest in such device.
>
Hi,
I've been working already on a synchronized_value class that is in trunk
[1]. I plan to merge it to release branch as soon as I have finished the
tests and the documentation. You can see some examples in [2] and [3].
I've take a look to your class and I think my class provides everything
yours provide.
My class allows in addition to lock several synchronized values using
the deadlock free lock algorithm as e.g.
class Person3 {
public:
Person3(unsigned int age) :
age_(age)
{ }
std::string GetName() const {
Invariant();
return name_;
}
void SetName(const std::string& newName) {
Invariant();
name_ = newName;
}
private:
std::string name_;
unsigned int age_;
void Invariant() const {
if (age_ < 1) throw std::runtime_error("Age cannot be negative");
}
};
typedef boost::synchronized_value<Person3> Person3_ts;
int main() {
Person3_ts p1(1);
Person3_ts p2(2);
Person3_ts p3(3);
auto lk1 = p1.unique_synchronize(boost::defer_lock);
auto lk2 = p2.unique_synchronize(boost::defer_lock);
auto lk3 = p3.unique_synchronize(boost::defer_lock);
boost::lock(lk1,lk2,lk3);
lk1->SetName("Carmen");
lk2->SetName("Javier");
lk3->SetName("Matias");
}
Please could you compare your class to mine and let me know what do you
think?
Best,
Vicente
[1]
https://svn.boost.org/svn/boost/trunk/boost/thread/synchronized_value.hpp
[2]
https://svn.boost.org/svn/boost/trunk/libs/thread/example/synchronized_value.cpp
[3]
https://svn.boost.org/svn/boost/trunk/libs/thread/example/synchronized_person.cpp
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