Question

I have:

struct employee
{
  uint64_t id;
  uint32_t a;
  uint32_t b;

  employee() { }

  struct By_id {};
  struct By_a {};
  struct By_b {};

  struct Change_a : public std::unary_function< employee, void >
  {
    uint32_t p;
    Change_a(const uint32_t &_p) : p(_p) {}
    void operator()(employee & r) { r.a = p; }
  };  

  struct Change_b : public std::unary_function< employee, void >
  {
    uint32_t p;
    Change_a(const uint32_t &_p) : p(_p) {}
    void operator()(employee & r) { r.b = p; }
  };   
};

typedef multi_index_container<
  employee,
  indexed_by<
    ordered_unique< tag<employee::By_id>, member<employee, uint64_t, &employee::id> >,
    ordered_non_unique< tag<employee::By_a>, member<employee, uint32_t, &employee::a> >,
    ordered_non_unique< tag<employee::By_b>, member<employee, uint32_t, &employee::b> >,
    >
> employee_set;

employee_set es;

typedef employee_set::index<employee::By_id>::type List_id;
typedef employee_set::index<employee::By_a>::type List_a;
typedef employee_set::index<employee::By_b>::type List_b;

//...
thread 1
List_id::iterator it_id;
es.modify( it_id, employee::Change_a( 0 ) );
thread 2
List_id::iterator it_id;
es.modify( it_id, employee::Change_b( 0 ) );
//...

This standart example how to work with boost multi index container. if find some node by id and store iterator in List_id::iterator it_id;

I want to change (modify) different fields of employee in different threads.

Does the concurent operations are thread safe?

Was it helpful?

Solution

Boost.MultiIndex has the same very basic thread safety guarantees than other containers in the standard library:

  • Concurrent read-only access is OK.
  • Concurrent write access must be externally synchronized by the user (you).

So, calls to modify (or any other operation resulting in changes in the container) must be guarded with some mutex-like mechanism.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top