I designed a class to have easier and most importantly more robust control of access to objects by more than one thread.
The design decisions are the following: 1. It should not be possible to make mistakes. Easy to make mistakes should result in a compile error. 2. In order to avoid two thread waiting on easy other while both just want to read, the interface must support read/write locking. 3. Locking and getting access to the data must be the same thing, and be achieved by means of creating an object. Leaving the scope will both, destroy the access object as well as release the locks, automatically. Typical usage code will look as follows: // Instantiation of an object Foo. LLThreadSafe<Foo> foo(new Foo); // Obtaining write access to the object. LLAccess<Foo> write_foo(foo); write_foo->x = 3; // Obtaining read access to the object. LLAccess<Foo, readaccess> read_foo(foo); std::cout << read_foo->x << std::endl; // Obtaining (temporary) write access without // giving up read access. LLAccess<Foo> write_foo(read_foo); // Obtaining read access to a constant foo. // Here foo_const has the type LLThreadSafe<Foo> const. LLAccess<Foo, readaccess_const> read_foo_const(foo_const); There is no way to access the instance of Foo than through LLAccess, and there is no way to create those without the proper locking. Obtaining a read lock will only allow to access const members. Of course it is possible to circumvent the safety precautions by using a const_cast, or by deliberatedly obtaining a pointer to the underlaying Foo, but that would be done deliberate and never by accident; for example: Foo foo1; LLThreadSafe<Foo> foo(&foo1); // Garanteed crash upon destruction of foo. Foo* foo1 = new Foo; LLThreadSafe<Foo> foo(foo1); // Should never ever make it through a review. LLAccess<Foo, readaccess> read_access(foo); const_cast<Foo*>(read_access::operator->())->write_access(); // Dream on Comments?
_______________________________________________ Policies and (un)subscribe information available here: http://wiki.secondlife.com/wiki/OpenSource-Dev Please read the policies before posting to keep unmoderated posting privileges