gpt4 book ai didi

boost - 是否在 boost multi_index 中修改不同的字段值线程安全

转载 作者:行者123 更新时间:2023-12-01 09:25:29 24 4
gpt4 key购买 nike

我有:

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 ) );
//...

这个标准示例如何使用 boost 多索引容器。如果通过 id 找到某个节点并将迭代器存储在 List_id::iterator it_id 中;

我想在不同的线程中更改(修改)员工的不同字段。

并发操作是线程安全的吗?

最佳答案

Boost.MultiIndex 与标准库中的其他容器具有相同的非常基本的线程安全保证:

  • 可以并发只读访问。
  • 并发写入访问必须由用户(您)进行外部同步。

因此,对 modify 的调用(或导致容器发生变化的任何其他操作)必须使用一些类似互斥锁的机制来保护。

关于boost - 是否在 boost multi_index 中修改不同的字段值线程安全,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23265044/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com