Simply adding a mutex lock in every accessor wouldn't really make them thread-safe. Consider: if (my_message.has_foo()) { DoSomething(my_message.foo()); }
This is not thread-safe if my_message can be modified in a separate thread *even if* each accessor locked a mutex, because "foo" could be cleared in another thread between the call to has_foo() and the call to foo(). Here's a more dangerous example: for (int i = 0; i < my_message.foo_size(); i++) { DoSomething(my_message.foo(i); } Here, if "foo" is cleared between the call to foo_size() and the call to foo(i), then the program will crash. Having a mutex protecting each individual accessor does not help. Another problem is that strings are returned by reference. So even if the accessor itself locks a mutex, the string's contents may be accessed after the accessor returns, and if they are simultaneously modified in another thread you'll get a crash. What you really need to do is maintain your own mutex at a higher level. Any thread which reads the message object needs to take out a reader lock before it starts reading and hold that lock until it is completely done accessing the object. Similarly, any thread writing to a message object needs to take a writer lock on that mutex at a higher level. The protobuf library can't really do anything to help here, since the correct mutex usage depends entirely on your application code. On Mon, Jun 29, 2009 at 10:01 AM, Jes <damealpi...@hotmail.com> wrote: > > Hi everybody, > > we are working on a distributed environment that uses PB, where > different threads will access to the contents of messages that can be > updated at any moment through the network. > > I wonder if there is an easy way to transform the (derived) Messages > into a thread-safe version. Maybe the rough solution could be to > include a Mutex in the Message class and a MutexLock on each method of > the generated pb.h and pb.cc classes, but perhaps there are issues > that can break the safety of this approach (such as existing friends > or similar). > > Could you have any suggestion on this? :-) > > Thanks in advance! > > Jes > > > > > --~--~---------~--~----~------------~-------~--~----~ You received this message because you are subscribed to the Google Groups "Protocol Buffers" group. To post to this group, send email to protobuf@googlegroups.com To unsubscribe from this group, send email to protobuf+unsubscr...@googlegroups.com For more options, visit this group at http://groups.google.com/group/protobuf?hl=en -~----------~----~----~----~------~----~------~--~---