寻找像fetch_add for atomic< double> [英] Looking for something like fetch_add for atomic<double>

查看:102
本文介绍了寻找像fetch_add for atomic< double>的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一些加法操作原子双打。
可悲的是:

I'm looking for some sort of an add-operation working on atomic doubles. Sadly:

myatomdouble += toadddouble;

未定义,

myatomdouble = myatomdouble + toadddouble;

被多线程拧紧,fetch_add只能用于整数类型,但不能用于双精度类型。但是类似fetch_add的东西正是我需要的。 :(

gets screwed by multithreading and fetch_add is only available for integral types, but not for doubles. But something like fetch_add would be exactly what I need. :(

并且互斥每次尝试修改变量会使程序变得不可读,代码不可读,并破坏了原子的想法。

and mutexing every attempt to modify the variable makes the program superslow, the code unreadable and destroys the idea of atomic.

这个问题有没有解决方案?

So is there any solution for this problem?

推荐答案

通用对象。

template<typename T>
T atomic_fetch_add(std::atomic<T> *obj, T arg) {
  T expected = obj->load();
  while(!atomic_compare_exchange_weak(obj, &expected, expected + arg))
    ;
  return expected;
}

虽然不能保证 atomic< double> 不使用互斥体,因此您必须检查您的实现。

Although there's no guarantee that atomic<double> doesn't use mutexes, so you'd have to check your implementation.

这篇关于寻找像fetch_add for atomic&lt; double&gt;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆