design - C++/Boost: Synchronize access to a resource across multiple method (getter) calls -


i'm not sure if question regarding programming technique or design i'm open suggestions.

the problem: want create abstraction layer between data sources (sensors) , consumers. idea consumers "know" interfaces (abstract base class) of different sensor types. each of sensor types consists of several individual values have own getter methods.

as example use simplified gps sensor.

class igpssensor {      public:         virtual float getlongitude() = 0;         virtual float getlatitude() = 0;         virtual float getelevation() = 0;          // deviations         virtual float getlongitudedev() = 0;         virtual float getlatitudedev() = 0;         virtual float getelevationdev() = 0;          virtual int getnumofsatellites() = 0; }; 

since updates sensor done different thread (details implementation of interface), synchronizing getters , update methods seems reasonable approach ensure consistency.

so far good. in cases level of synchronization should suffice. however, might necessary aquire more 1 value (with consecutive getxxx() calls) , ensure no update happening in between. whether necessary or not (and values important) consumer.

sticking example, in lot of cases important know longitude , latitude (but both relating same update()). admit done grouping them "position" class or struct. consumer might use sensor more complicated algorithm , requires deviation well.

now wondering, proper way this.

solutions think of:

  • group possible values struct (or class) , add additional (synchronized) getter returning copies of values @ once - seems lot of unnecessary overhead me in case 2 or 3 out of maybe 10 values needed.

  • add method returning reference mutex used within data source allow locking consumer - doesn't feel "good design". , since getters synchronized, using recursive mutex mandatory. however, assume there multiple readers 1 writer , i'd rather go shared mutex here.

thanks help.

how exposing "reader" interface? reader object, this:

const igpssensorreader& gps_reader = gps_sensor.getreader(); 

the igpssensorreader class have access protected members of igpssensor class. when constructed, acquire lock. upon destruction, release lock. accessor this:

{ //block accesses attributes    const igpssensorreader& gps_reader = gps_sensor.getreader();    //read whatever values gps_reader needs } //closing scope destruct gps_reader, causing unlock 

you expose getwriter method thread doing updates. internally, use boost's shared_mutex mediate access between readers , writers.


Comments

Popular posts from this blog

c++ - Is it possible to compile a VST on linux? -

java - Output of Eclipse is rubbish -

jquery - Confused with JSON data and normal data in Django ajax request -