ROS Resources: Documentation | Support | Discussion Forum | Index | Service Status | ros @ Robotics Stack Exchange
Ask Your Question
2

why pr2-controllers use a shared pointer + realtimebox ?

asked 2011-05-11 21:10:54 -0500

Guido gravatar image

updated 2013-06-05 03:16:50 -0500

130s gravatar image

Hi all,

As I further explore controllers, I notice that shared access is made possible by a realtimebox containing a shared pointer. If I understand correctly, the realtimebox uses a mutex for thread safety. However the shared pointer, too, offers multiple access protection. This seems redundant to me. Maybe I'm missing something ? Why is it done this way ?

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
3

answered 2011-06-02 12:36:21 -0500

sglaser gravatar image

Hi Guido,

Some uses of boost::shared_ptr are thread safe, but other uses are not.

The documentation for shared pointers describes which operations are thread safe:

A shared_ptr instance can be "read" (accessed using only const operations) simultaneously by multiple threads. Different shared_ptr instances can be "written to" (accessed using mutable operations such as operator= or reset) simultaneosly by multiple threads (even when these instances are copies, and share the same reference count underneath.)

These are the two things you can do with a shared pointer: access it without changing it and modify separate shared pointer instances simultaneously. The realtime box solves a third use case: passing an instance of a shared pointer from one thread to another.

Consider the following scenario. Two threads share a global shared pointer named ptr. Thread A writes to ptr, and thread B reads from it:

=== Thread A

ptr.reset(new Object);

=== Thread B

my_ptr = ptr;

This is not guaranteed to be thread safe because shared pointer assignment is not atomic. The assignment to my_ptr can occur at the same time that thread A is modifying ptr, leading to a corrupted shared pointer.

If you're still doubtful, here is a stackoverflow question with a similar example.

edit flag offensive delete link more

Comments

So that's what I was missing :). Thanks for the answer.
Guido gravatar image Guido  ( 2011-06-06 21:33:06 -0500 )edit

Question Tools

Stats

Asked: 2011-05-11 21:10:54 -0500

Seen: 322 times

Last updated: Jun 02 '11