How to easy make this counter property thread safe?

前端 未结 5 2335
陌清茗
陌清茗 2021-02-20 08:31

I have property definition in class where i have only Counters, this must be thread-safe and this isn\'t because get and set is not in same lock, How t

5条回答
  •  粉色の甜心
    2021-02-20 09:26

    If you're expecting not just that some threads will occasionally write to the counter at the same time, but that lots of threads will keep doing so, then you want to have several counters, at least one cache-line apart from each other, and have different threads write to different counters, summing them when you need the tally.

    This keeps most threads out of each others ways, which stops them from flushing each others values out of the cores, and slowing each other up. (You still need interlocked unless you can guarantee each thread will stay separate).

    For the vast majority of cases, you just need to make sure the occasional bit of contention doesn't mess up the values, in which case Sean U's answer is better in every way (striped counters like this are slower for uncontested use).

提交回复
热议问题